Search code examples
c#interfacedefault

Purpose of default(IInterface) in C#


If you have an interface called - for example - IInterface, in C# it is perfectly legal to write code like this:

var i = default(IInterface);

But it always returns null.

What is the purpose of allowing such an expression with that unique result? An interface can be implemented also by numeric or struct classes, a default null is not usable. So... what are the reasons beyond the choice to allow default(IInterface) in the language?


Solution

  • The default(T) operator was introduced for generic types.

    If T is a type parameter, it will return null for reference types or new T() for value types.

    Once the operator exists, there is no reason to limit it to only work with type parameters, so it works with all types.