3

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?

Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
  • 1
    Interfaces are reference types: [Structs, Interfaces and Boxing](http://stackoverflow.com/questions/3032750/structs-interfaces-and-boxing). – Pieter Witvoet Nov 07 '16 at 15:27
  • 1
    Crucial in generic code. And pretty handy when you need to convert VB.NET code that uses Nothing. Or if you have an optional argument of type IntPtr, can't use IntPtr.Zero. – Hans Passant Nov 07 '16 at 15:32

1 Answers1

8

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • The part that I would deep is "there is no reason to limit"... because you can make every feature more flexibile and wider, but it costs in terms of development, maintenance, learning curve, and so on. "There is no reason to limit" is an opinion-based _negative_ argument, I'm looking for some _positive_ argument to allow such a syntax. – Massimiliano Kraus Nov 07 '16 at 16:00