Interface Question


J

JasonX

Hi,

Im just going through my old exam papers, and have come by a question
that asks to explain how you would use a variable of type IMyInterface

for example given this interface

interface IMyInterface
{
string DoWork();
}

and this class that inherits off it:

class MyClass : IMyInterface
{

....

How would you use a variable of type IMyInterface?

i.e IMyInterface imf = ...?

I dont see what possible use imf would have or how i would use it? Or
could the question simply mean you would use a variable of type
IMyInterface by going "class MyClass : IMyInterface"?

Thanks for any help,
Jason
 
Ad

Advertisements

R

Roland Dick

Hi Jason,
interface IMyInterface
{
string DoWork();
}

and this class that inherits off it:

class MyClass : IMyInterface
{

...
I dont see what possible use imf would have or how i would use it? Or
could the question simply mean you would use a variable of type
IMyInterface by going "class MyClass : IMyInterface"?

in the simplest form, you would use it like in
IMyInterface myobject = new MyClass();

It starts to make sense when you have a second class that inherits from
the same interface:
class MyOtherClass : IMyInterface

Then you can have something like this:

IMyInterface myobject = null;
if (UserSelected==1)
myobject = new MyClass();
else
myobject = new MyOtherClass();

// here, you don't care any more what class the object is from
myobject.DoWork();

The classes can implement completely different functionality, but they
have to implement the DoWork() method. This proves to be extremely
useful e.g. when your applications offer a plug-in mechanism or connect
to different other software (e.g. Oracle and SQL Server or Outlook and
Lotus Notes) etc.

Hope this helps,

Roland
 

Top