Search code examples
c#interfacereturn-valuevalue-typereference-type

Method return default value


Why am I allowed to return null within a method declaration, which could also return a value type?
I thought interfaces such as IList<T> have no restriction on the type of their implementation.
Further, how would one check if a method returning a IList<T> returned the default value?

public IList<int> SomeMethod()
{
    // Allowed
    return new MyStructList();

    // Allowed
    return null;
}

public struct MyStructList : IList<int>
{
   ...
}

Solution

  • Your SomeMethod method returns an IList<int>. IList<T> is an interface, which is a reference type. null is an allowable value for a reference type.

    When you do return new MyStructList(), that's essentially shorthand for:

    IList<int> ret = new MyStructList();
    return ret;
    

    That IList<int> ret = new MyStructList(); boxes MyStructList(): a box is allocated for it, the MyStructList is copied into the box, and a reference to the box is created and assigned to ret. This is necessary, as ret has type IList<int>, and IList<T> is a reference type, so ret can only contain references.