1

I have a class implementing an interface. I don't need a reference to objects of that class - only reference to their interfaces. It looks like:

interface A {}

class B : A {}

//in code:
A a = (A) new B();

My question is: Will instance of B to live (not collecting by GC) while I have a reference to A of that B?

Tadeusz
  • 6,453
  • 9
  • 40
  • 58
  • 3
    You can't have a reference to an interface. You can have a reference to an object implementing an interface. – Oded Sep 30 '11 at 09:11
  • @Ace - I don't think the question ever suggested creating such; but actually, in *interop* code you *can* `new()` an interface (there's a hack in the compiler for this): http://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-or-net/1281522#1281522 – Marc Gravell Sep 30 '11 at 09:15

4 Answers4

4

Yes, because you still have a reference to that new B() although you can see only the part that implements that interface A.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
1

The reference is the same actual value no matter whether your variable is typed as the class or the interface. So yes: it will stay alive.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

yes the instance of the object is the same, you can cast the object to any of its implemented interface, but the instance is one.

Massimo Zerbini
  • 3,125
  • 22
  • 22
1

Yes, because a reference to an object through an interface is still a reference to that object.

Casting an object to an interface does not create a new object, it just alters the "portal" you use to talk to the object through.

You can easily test this in LINQPad:

void Main()
{
    A a = (A)new B();
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
    GC.KeepAlive(a);
    Debug.WriteLine("Got here");
}

public interface A
{
}

public class B : A
{
    ~B()
    {
        Debug.WriteLine("B was finalized");
    }
}

When executed, you'll get:

Got here

And then, optionally:

B was finalized

But notice that B survived the full GC cycle, even though you had a reference to it through A.

Community
  • 1
  • 1
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • Casting a class-type object to an interface does not create a new object; as you note, the compiler knows to regard the thing in question as an interface, but it's still the same thing. Casting a structure to an interface does, however, create a new object disjoint from the original. For this reason, structures should seldom implement interfaces except when generics can allow the interface to be used without a typecast (as with IComparable). – supercat Sep 30 '11 at 14:34
  • Which is why I said 'object', but yes, structures are different. – Lasse V. Karlsen Sep 30 '11 at 16:47