Should I use default (Foo), Foo.Empty or null?

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

+3
source share
3 answers

default(Foo)will return null if Foo- the type of the class, zero, where Foo- the type of value (for example, int), and an instance Foowith all the fields initialized by their respective default()where Foois the structure. It was added to the language so that generics could support both values ​​and reference types - more information on MSDN

Use default(Foo)when you are testing T in the context of SomeClass<T>or MyMethod<T>, and you do not know if T will be a value type, class type, or structure.

null "", " , ". Foo.Empty, , ; String.Empty "", .

null, , (), , .

+16

default(Foo) , . New Foo(), null Foo.Empty() . , , , . null, , .

+2

, , ": class", (null, 0 ..).

, , , (T).

+2

Source: https://habr.com/ru/post/1698115/


All Articles