Hi I am slightly confused about interfaces for an inheritance structure. Firstly can anyone explain there purpose, secondly can anyone demonstrate there use.

I have created an application that uses reflection to dynamically instantiate classes and invoke methods within those classes. During research for this app I cam accross interfaces but was lost at there purpose and the syntax of there use.

I would be greatful if anyone can help. Thanks

Recommended Answers

All 4 Replies

Hi I am slightly confused about interfaces for an inheritance structure. Firstly can anyone explain there purpose, secondly can anyone demonstrate there use.

I have created an application that uses reflection to dynamically instantiate classes and invoke methods within those classes. During research for this app I cam accross interfaces but was lost at there purpose and the syntax of there use.

I would be greatful if anyone can help. Thanks

You can use interfaces to structure up your programming when using polymorphism and to pass objects that are different but who all have some methods that are defined in the interface.

Example: http://www.codersource.net/csharp_tutorial_interface.html

Just to add to this:

If you're using reflection frequently because you have several classes that have the same method, you could consider casting those objects up to a defined interface. Say you have two classes, ClassA and ClassB. Both classes have a method called Run(), which you've defined in an interface called IRunnable:

public interface IRunnable
{
     public void Run();
}

ClassA a = new ClassA();
ClassB b = new ClassB();

//casting up to IRunnable
IRunnable aR = (IRunnable)a;
IRunnable bR = (IRunnable)b;

//you could then pass these IRunnables to any method that takes an IRunnable as a parameter, for instance.

private static void MakeRun(IRunnable r)
{
     r.Run();
}

MakeRun(aR);
MakeRun(bR);

...This is a really simple example, but I hope you get a good idea. You can do similar things with Interfaces that you can do with Reflection. I think it's cleaner to use Interfaces because you then have type-safety when executing those methods when returning values and inputting parameters.

Hi there thank you all for your input. I understand interfaces a bit better now, so thank you again.

Jon

as u mentioned in the above example parameters are same ,methods also same..is it runtime polymorphisim? can we achieve polymorphisim thru interfaces

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.