473,769 Members | 3,352 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Beginner interface question

I've been reading up on interfaces, one example I came across showed
that you can hide a method implemented from an interface from the class
which implements it. To use it, you must cast to the interface type
e.g.:

interface IFoo
{
void display();
}

class Blah : IFoo
{
void IFoo.display()
{
System.Console. WriteLine("hell o");
}
}

class MainApp
{
public static void Main()
{
Blah myBlah = new Blah();

myBlah.display( ); //error
((IFoo)myBlah). display(); //works
}
}

In what circumstances would you ever want to do this? The place I found
this didn't explain why this would ever be done.
Sorry if these questions are missing the obvious :).

Chris

Dec 12 '05 #1
13 1765
The circumstances you would use an Interface in such a manner, is when
there is a need to limit accessibility to methods.

For example, suppose your "Blah" class was an abstraction of a
Database. Inside that class would be "Delete", "Create", "Update",
"Insert", "Select" functions. Now whoever uses the "Blah" object can
do some serious damage to the Database if they are not careful. So to
limit damage you might want to create an interface. Possible
interfaces would be as follows :

IDbAdmin -> Has access to all functions
IReadOnlyUser -> Has access to "Select" functions only.
IUpdateOnlyUser -> Has access to "Update" / "Insert" functions only.
ICreateOnlyUser -> Has access to "Create" functions only.
etc..

You can also chose to not create a "Delete" interface because you may
decide only admins have access to that feature.

I believe this is what they call a FACADE pattern.

Hope this was a good practical example.

enjoy,
Josh Go

Dec 12 '05 #2
I have the same Problem, and cannt figure it out as i am new to
Interfaces,

Classes:

1-DataRepository Class - Contains (GetClientInfo Method, GetOrderInfo
Method)
2-Client Class
3-Order Class

The DataRepository Class has all the Functions that deals with the
Database such as (Client & Order) database methods.

Required:

make the Client Class have only Access to the GetClientInfo Method
and not also the GetOrderInfo Method and vice versa

How to do it using Interfaces??

can u please show it in code, as i am new to Interfaces

Sharing makes All the Difference

--
Sent via .NET Newsgroups
http://www.dotnetnewsgroups.com
Dec 12 '05 #3
Hey Dave,

I replied to your original post about FACADEs.

Here is some sample code. In this example I create a "TextFile" object
which is an abstraction of a normal text file on disk. Now every file
on your computer has "Access" rights. I simulated those access rights
with interfaces. So in this example, there is a "IReadOnlyUser" ,
"IWriteOnlyUser ", and "IFileAdmin " interface. The first 2 interfaces
are pretty self-explanatory and the IFileAdmin is just an interface
that has both read/write capabilities.

using System;

namespace CS_InterfaceTes t
{
#region interfaces

interface IFileAdmin : IReadOnlyUser, IWriteOnlyUser{ }

interface IReadOnlyUser
{
void PrepareForRead( );
string ReadLine();
void CloseRead();
}
interface IWriteOnlyUser
{
void PrepareForWrite ();
void WriteLine(strin g p_String);
void CloseWrite();
}

#endregion

#region textfile class

class TextFile : IFileAdmin
{
private string m_Filename;
private System.IO.Strea mReader m_StreamReader;
private System.IO.Strea mWriter m_StreamWriter;

#region properties

public string Filename
{
get{return m_Filename;}
set{m_Filename = value;}
}

#endregion

#region read access

void IReadOnlyUser.P repareForRead()
{
m_StreamReader = new System.IO.Strea mReader(this.Fi lename);
}
string IReadOnlyUser.R eadLine()
{
string buff = null;
if( m_StreamReader. Peek() != -1 )
{
buff = m_StreamReader. ReadLine();
}
return buff;
}
void IReadOnlyUser.C loseRead()
{
m_StreamReader. Close();
}

#endregion

#region write access
void IWriteOnlyUser. PrepareForWrite ()
{
m_StreamWriter = new System.IO.Strea mWriter(this.Fi lename,
true);
}
void IWriteOnlyUser. WriteLine(strin g p_String)
{
m_StreamWriter. WriteLine(p_Str ing);
}
void IWriteOnlyUser. CloseWrite()
{
m_StreamWriter. Close();
}
#endregion

}

#endregion

#region main/testing code
class MainClass
{
[STAThread()]
public static void Main()
{
TextFile file = new TextFile();
file.Filename = "foo.txt";

Console.WriteLi ne("---- Admin Test ----");
FullyTrustedUse r((IFileAdmin)f ile);

Console.WriteLi ne("");

Console.WriteLi ne("---- Write Test ----");
SemiTrustedUser ((IWriteOnlyUse r)file);

Console.WriteLi ne("");

Console.WriteLi ne("---- Read Test ----");
UntrustedUser(( IReadOnlyUser)f ile);
}

//demonstrate read/write access
public static void FullyTrustedUse r(IFileAdmin p_Admin)
{
//Write something
p_Admin.Prepare ForWrite();
p_Admin.WriteLi ne("I am the admin");
p_Admin.CloseWr ite();

//Read it out
p_Admin.Prepare ForRead();
string buff = p_Admin.ReadLin e();

while( buff != null)
{
Console.WriteLi ne(buff);
buff = p_Admin.ReadLin e();
};
p_Admin.CloseRe ad();
}

//demonstrate read access
public static void UntrustedUser(I ReadOnlyUser p_Read)
{
p_Read.PrepareF orRead();
string buff = p_Read.ReadLine ();

while( buff != null)
{
Console.WriteLi ne(buff);
buff = p_Read.ReadLine ();
};
p_Read.CloseRea d();
}

//demonstrate write access
public static void SemiTrustedUser (IWriteOnlyUser p_Write)
{
p_Write.Prepare ForWrite();
p_Write.WriteLi ne("I am not fully trusted");
p_Write.CloseWr ite();
}
}
#endregion
}

Dec 12 '05 #4
yoshig... one caution, limiting access through the type of a reference
is a weak guarantee. once I have access to the reference of the limited
type, I can just cast it to the type of the full reference.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Dec 12 '05 #5
How about:

using System;
using System.Collecti ons.Generic;
using System.Text;

namespace LimitedAccess
{
interface IData
{
int ClientInfo { get;set;}
int OrderInfo { get;set;}
}
interface IClient
{
int ClientInfo { get;}
}
interface IAdministrator
{
int ClientInfo { get;set;}
int OrderInfo { get;set;}
}
// not thread safe
class Data : IData
{
private int clientInfo = 0;
private int orderInfo = 0;
public Data(int clientInfo, int orderInfo) {
this.clientInfo = clientInfo;
this.orderInfo= orderInfo;
}
public int ClientInfo
{
get { return this.clientInfo ; }
set { this.clientInfo = value; }
}
public int OrderInfo
{
get { return this.orderInfo; }
set { this.orderInfo = value; }
}
}
class Client : IClient
{
private IData data = null;
//ASSERT data not null
public Client(IData data)
{
if (data == null) { throw new ArgumentExcepti on(); }
this.data = (Data)data;
}
public int ClientInfo
{
get { return data.ClientInfo ; }
}
class Administrator : IAdministrator
{
private IData data = null;
// ASSERT data not null
public Administrator(I Data data)
{
if (data == null) { throw new ArgumentExcepti on(); }
this.data = data;
}
public int ClientInfo
{
get
{
return data.ClientInfo ;
}
set
{
this.data.Clien tInfo = value;
}
}
public int OrderInfo
{
get { return this.data.Order Info; }
set { this.data.Order Info = value; }
}

static void Main(string[] args)
{
IData data= new Data(2,3);
Administrator adm = new Administrator(d ata);
Client c = new Client(data);
System.Console. WriteLine(adm.O rderInfo);
System.Console. WriteLine(c.Cli entInfo);
//System.Console. WriteLine(c.Ord erInfo); // error Client
does not contain a definition...
System.Console. ReadLine();
}
}
}
}
Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Dec 12 '05 #6
Hey Jeff,

You are totally correct and thanks for pointing that out. Interfaces
are not the way to go for "securing access". I should have picked a
better example than "read/write access"...sorry about that.
The idea behind my solution was to be able to relate a bunch of
functions, but still deal with the exact same object.

I actually like your example, it's very clear and assertive. The data
and logic are completely broken as they should be.

Now as for Dave Johnson's request...the 2nd post. What's your take on
that?

Dec 12 '05 #7
Hmm... A correction:

private IData data = null;
//ASSERT data not null
public Client(IData data)
{
if (data == null) { throw new ArgumentExcepti on(); }
this.data = data; // no need to cast to (Data)
}

So you can pass any concrete class that implements IData.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Dec 12 '05 #8
Here's how I would use explicit interface implementation

1. the obvious one is to avoid method collision. when two interfaces have
the same method defined, but will require different implementations .
although I don't remember ever run into this situation.
2. if the member should be exposed using an alternative name better suited
in the context of the object that implements it. I'd hide the interface name
instead of exposing both.
3. if a method is rarely / never called directly off of the object, most
times it's something required for the framework support and used indirectly
by something else. IComparable.Com pareTo is always a good candidate for that.
4. related to 3, when implementing an internal interface. typically, these
should always be hidden from the consumers.

"^MisterJin go^" wrote:
I've been reading up on interfaces, one example I came across showed
that you can hide a method implemented from an interface from the class
which implements it. To use it, you must cast to the interface type
e.g.:

interface IFoo
{
void display();
}

class Blah : IFoo
{
void IFoo.display()
{
System.Console. WriteLine("hell o");
}
}

class MainApp
{
public static void Main()
{
Blah myBlah = new Blah();

myBlah.display( ); //error
((IFoo)myBlah). display(); //works
}
}

In what circumstances would you ever want to do this? The place I found
this didn't explain why this would ever be done.
Sorry if these questions are missing the obvious :).

Chris

Dec 12 '05 #9
Thanks for the replies all, it makes more sense now. I thought it might
be a bit 'fiddly' casting to the interface type to call certain
methods, but after playing around, I found out this:

public interface IShape
{
double area();
double circumference() ;
int sides();
void blah();
}

public class Oblong :IShape
{
public int side;

public double area() { return (double)((side * side) * 2); }

public double circumference() { return ((double)(6 * side)); }

public int sides() { return 4; }
public Oblong() { side = 0;}

void IShape.blah(){ Console.WriteLi ne("Test"); }
}

public class Shape
{
public static void Main(string[] args)
{
Oblong myOb = new Oblong();
myOb.side = 5;
Console.WriteLi ne("Displaying Info:");
displayInfo(myO b);
}

static void displayInfo(ISh ape myShape)
{
Console.WriteLi ne("Area: {0}", myShape.area()) ;
Console.WriteLi ne("Sides: {0}", myShape.sides() );
Console.WriteLi ne("Circumferen ce: {0}",
myShape.circumf erence());
myShape.blah();
}
}

using a method taking the interface type, I can perhaps see uses for
that.

A quick question:
If I had a number of objects which were not derived from the same base
class. Each of these objects had a load and save method, which were
called on every instanced object when the user selected a save event.
Would it be best to create a load/save interface, and then use a method
such as above. Or would it be best to use a function which calls every
object in turn, decides what form the object is and then load/save. Or
even factoring all objects which need load and save functionality into
a common base class? (the load or save could be something like
drawToScreen etc).

I'm trying to get my head around when best to use interfaces etc.

Thanks,

Chris

Dec 12 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2871
by: Art | last post by:
NEWBIE ALERT! Esteemed List Participants and Lurkers: (System: P-II 350, 192 meg, Win98 SE, Python 2.2.3, wxPythonWIN32-2.4.1.2-Py22.exe) I'm having a lot of fun getting started with Python ... it is the most elegant and graceful language I have ever used (Fortran, Cobol, Basic, many assemblers, Forth, C, VB, etc.). I don't have the resources or the
5
1639
by: Timothy Wu | last post by:
I'm writing a small utility that listens for socket connections, and also repond to user inputs via a text menu selection. In order to respond to both the user and the incoming connections I figure I need to use thread. I think I would use the main thread to handle the menu and spawn a thread which listens on a socket. Now my question is, how do I terminate the server thread if user wants
0
3724
by: Jari Kujansuu | last post by:
I am trying to learn to use jing through JARV interface and I have read JARV User's Guide (http://iso-relax.sourceforge.net/JARV/JARV.html). I have downloaded jingjarv-examples.zip from JARV User's Guide page and latest jing version 20030619 from jing home page. I can run jing successfully from command line like this (which I guess proves that schema should be correct) C:\Temp\APU> java -jar jing.jar schema.xsd valid.xml
44
4280
by: lester | last post by:
a pre-beginner's question: what is the pros and cons of .net, compared to ++ I am wondering what can I get if I continue to learn C# after I have learned C --> C++ --> C# ?? I think there must be many know the answer here. thanks
2
1166
by: Paul | last post by:
Hi, I'm curious how others would deal with something I'm building. The app itself is a form of diary; it allows the organisation of diary entries and a number of other data types. Each diary entry is listed under its title, and double clicking brings up the full entry and options for editing. Each entry and associated option is stored in a diary object instance. I'm wondering how best to store the persistent data. One option is to a...
9
5519
by: hharry | last post by:
hello all, switching to c# from vb.net and had quick syntax question... in vb: Dim httpRequest as HttpWebRequest httpRequest = WebRequest.Create( _ "http://www.winisp.net/goodrich/default.htm")
6
3008
by: Qun Cao | last post by:
Hi Everyone, I am a beginner on cross language development. My problem at hand is to build a python interface for a C++ application built on top of a 3D game engine. The purpose of this python interface is providing a convenient scripting toolkit for the application. One example is that a user can write a python script like: player = Player() game.loadPlayer(player) player.moveTo(location)
4
3991
by: Jan | last post by:
Yesterday I got the idea to use remoting for the test interface between our Windows Xp Embedded - based device and our system test application. I started looking in the MSDN help and made the code below. My server class (RemotingServer) is located in one assembly (LibS.dll) used by the device software and the test system will use another assembly (LibC.dll) including my client class (TestConnectionRemoting). We have NO security issues -...
1
2561
by: Robert J. Bonn | last post by:
I'm trying to set up a contact list in MS Access 97. I've looked through a reference book and the program's help screens, but the light bulb isn't quite coming on for me. If one of you could take the time to answer two very elementary questions, I'd appreciate it. Suppose the contact list consists of (for example) musicians and teachers. For every person in the list, we keep name, address, etc. For musicians, we keep track of what...
0
9579
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9416
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10032
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9979
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7393
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6661
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5293
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5433
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3948
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.