views:

161

answers:

3

So C# now allows you to use default(Foo) to get a recognized "not filled in yet"/empty instance of a class -- I'm not sure if it is exactly the same as new Foo() or not. Many library classes also implement a Foo.Empty property, which returns a similar instance. And of course any reference type can point to null. So really, what's the difference? When is one right or wrong? What's more consistent, or performs better? What tests should I use when checking if an object is conceptually "not ready for prime time"? Not everybody has Foo.IsNullOrEmpty().

+2  A: 

default(Foo) works for both value types and reference types. New Foo(), null and Foo.Empty() do not. This makes it a good choice for use with generic types, for example, when you may not know which you're dealing with. But in most reference-type cases, null is probably good enough.

Joel Coehoorn
+15  A: 

default(Foo) will return null when Foo is a class type, zero where Foo is a value type (such as int), and an instance of Foo with all fields initialized to their respective default() values where Foo is a struct. It was added to the language so that generics could support both value and reference types - more info at MSDN

Use default(Foo) when you're testing a T in the context of SomeClass<T> or MyMethod<T> and you don't know whether T will be value type, a class type or a struct.

Otherwise, null should mean "unknown", and empty should mean "I know this is empty". Use the Foo.Empty pattern if you genuinely need an empty - but non-null - instance of your class; e.g. String.Empty as an alternative to "" if you need to initialize some variable to the empty string.

Use null if you know you're working with reference types (classes), there's no generics involved, and you're explicitly testing for uninitialized references.

Dylan Beattie
+2  A: 

When you know the actual type involved, or if you've got a type parameter constrained with ": class" it's simplest to use the known value (null, 0 etc).

When you've just got a type parameter which is unconstrained or constrained other than to be a reference type, you need to use default(T).

Jon Skeet