jack
jack

Reputation: 491

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

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

Upvotes: 13

Views: 84329

Answers (2)

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 121057

Say you have the following classes:

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

public class GrannySmith : IApple{

    public GrannySmith()
    {
        this.I = 10;
        this.J = 6;
    }
    int I {get; set;}
    int J {get; set;}
}

public class PinkLady : IApple{

    public PinkLady()
    {
        this.I = 42;
        this.J = 1;
    }
    int I {get; set;}
    int J {get; set;}
}

public class FruitUtils{
    public int CalculateAppleness(IApple apple)
    {
         return apple.J * apple.I;
    }
}

now somewhere in your program you could write:

var apple = new GrannySmith();
var result = new FruitUtils().CalculateAppleness(apple);
var apple2 = new PinkLady();
var result2 = new FruitUtils().CalculateAppleness(apple2);

Console.WriteLine(result); //Produces 60
Console.WriteLine(result2); //Produces 42

Upvotes: 16

Richard Friend
Richard Friend

Reputation: 16018

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);

Upvotes: 43

Related Questions