Search code examples
c#interfacescopelanguage-theory

What is the basic C# interface scope?


I am having a dispute with another fellow programmer, over the scope of interfaces.

suppose we have the following:

public interface IFoo
{
    string Bar { get; set; }
}

public class SomeFoo: IFoo
{
    public string Bar { get; set; }

    public SomeFoo(string bar)
    {
        this.Bar = bar;
    }
}

public class Consumer
{
    public void DoSomething()
    {
        SomeFoo fooClassInstance = new SomeFoo("test");
        IFoo fooInterface = (IFoo)fooClassInstance;

        // do something with fooInterface.
    }
}

So the question is: 1. Is it possible the fooClassInstance to go out of scope before something else releases the fooInterface instance?

Some argue that the object (fooClassInstance) can go out of scope.

I believe that it cant. Sure, objects may or may not get disposed of by the GC when the GC decides that the object(s) are no longer in scope. However since Interfaces are by design an abstract contract whose members have to be implemented by the object that uses it, than an interface cannot lose its implementation so long as the interface is used. It's not like a whole another object is created of type "interface". The interface is merely a pointer to those abstract members of the implementor.

Can you guys help me resolve this dispute?

Thanks,

<bleepzter />

Solution

  • Uh, what do you mean by "lose its implementation"? That makes no sense. A type implements an interface, it cannot "unimplement" an interface.

    As far as your code example goes, the lifetime of the object allocated ends the instant it no longer has any roots (aka, is no longer reachable by the GC). A reference to it is a reference to it, regardless of the type of the reference (i.e. if the reference type is of some derived or parent type, it doesn't matter).

    ISomething Sample() {
        Something s1 = new Something();
        s2.DoSomething(); // Assuming s is the only reference to s, then it no longer is
                          // rooted after this expression
    
        Something s2 = new Something();
        ISomething is1 = s2;
        s2 = null;
        is1.DoSomething(); // The reference remains valid and the lifetime of the
                           // object created continues until we release all
                           // remaining references to it.
        return is1;
    }