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

I am new to C #. Could you tell me how to pass an interface as a parameter to a method?
that is, I want to access the members of the interface (property) and assign values ​​to it and send this interface as a parameter to another method.

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

Method (IApple var);

Is it possible? Sorry, if I am not good at basic, please help me. thanks in advance

+3
source share
2 answers

I am sure that 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);
+27
source

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
+6
source

Source: https://habr.com/ru/post/1786686/


All Articles