0

Why i can call Method? It can't see the implementation of the Method, only declaration, isn't it? Is it upcast and boxing at the same time.. or not?

interface IB
{
    void Method();
}

struct A : IB
{
    public void Method() { Console.WriteLine("1"); }
}

class Program
{
    static void Main()
    {
        A a;
        a.Method();
        IB i = a;   // boxing.. and upcast?
        i.Method(); // why it works? It looks like call of declaration
    }
}

Result of work:

1

1

Community
  • 1
  • 1
Amazing User
  • 3,473
  • 10
  • 36
  • 75

3 Answers3

2

When you assign your object to the instance of your interface i you are simply hiding anything else in the a object that doesnt match the interface definition.

Instead lets assume your struct was

struct A : IB
{
    public void Method() { Console.WriteLine("1"); }   // Method defined in interface IB. 

    public void Method2() { Console.WriteLine("2"); }  // Method only in A
}

class Program
{
    static void Main()
    {
        A a;
        a.Method();
        a.Method2();  // This works. 
        IB i = a;
        i.Method();
        i.Method2();// This fails to compile because Method2 isnt defined in the interface. 
    }
}
CathalMF
  • 9,705
  • 6
  • 70
  • 106
1

It looks like you are creating an instance of A, then calling the method in A, and then declaring IB(i) to be the instance of A and again calling its method

Mikael Puusaari
  • 854
  • 1
  • 10
  • 14
1

The instance of class A implements interface IB, that is to say, any instance of class A is also type of interface IB, so it is perfectly legitimate to assign object of A to IB. No casting. No boxing. And yes, as @CathalMF said, you will only be able to call what is there in IB interface from this object.

Yogi
  • 9,174
  • 2
  • 46
  • 61