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
Yes, you can pass Interface as a parameter in the function.
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".
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With