Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass an interface as a parameter to a method?

Tags:

c#

I am a newbie to C#. Could you please tell me how to pass an interface as a parameter to a method?
i.e. I want to access the interface members(property) and assign the values to it and send that interface as a parameter to another method.

Say for example if I have an interface as IApple which has members as property int i and int j I want to assign values to i and j and send the whole interface as a parameter say like this

Method(IApple var);

Is it possible? Sorry if am poor at basics please help me out. thanks in advance

like image 240
jack Avatar asked Jan 20 '11 14:01

jack


People also ask

Can we pass interface as a parameter to a method?

Yes, you can pass Interface as a parameter in the function.

Can I pass interface as a parameter in C#?

Interfaces can be only compile-time types because there one cannot create an object of interface type. Nevertheless, interface reference can represent an real object, only the run-time type of this object can be some structure or class implementing the interface. There is no such thing as "interface to a method".

Can you call a method from an interface?

In order to call an interface method from a java program, the program must instantiate the interface implementation program. A method can then be called using the implementation object.


1 Answers

Sure this is possible

public interface IApple
{
    int I {get;set;}
    int J {get;set;}
}

public class GrannySmith :IApple
{
     public int I {get;set;}
     public int J {get;set;}

}

//then a method

public void DoSomething(IApple apple)
{
    int i = apple.I;
    //etc...
}

//and an example usage
IApple apple = new GrannySmith();
DoSomething(apple);
like image 62
Richard Friend Avatar answered Oct 07 '22 02:10

Richard Friend