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().
So C# now allows you to use default(Foo) to get a recognized not filled
Share
default(Foo)will return null whenFoois a class type, zero whereFoois a value type (such as int), and an instance ofFoowith all fields initialized to their respectivedefault()values whereFoois a struct. It was added to the language so that generics could support both value and reference types – more info at MSDNUse
default(Foo)when you’re testing a T in the context ofSomeClass<T>orMyMethod<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.Emptyas 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.