Ali
Ali

Reputation: 3469

Different between keyword "new" and "default" in create instance of class

I have class like:

 class foo
    {
        public foo(string Text)
        {
        }
    }

After run this code for create instance of class the obj1 set to null:

foo obj1 = default(foo);

And by blow code everything work fine:

foo obj2= new foo("bla bla");

I have 2 Question :

  1. Whats happen to default contractor when run default(foo);?
  2. Is foo obj1 = default(foo); equal the foo obj1 = null?

Thanks in advance.

Upvotes: 2

Views: 789

Answers (4)

Kris
Kris

Reputation: 41877

In essence default(T) only reserves the minimum memory required to hold a reference to, or instance of the type, it does not call any constructors.

  • For primitive types like int and bool the value returned would be 0 or false respectively.
  • For reference types (classes) the only reservation made is for the reference, which will be null
  • For structs, the memory for the struct will be reserved according to the rules above, so reference fields will be initialized to null, even if they cannot normally be null because of a constructor! Value fields will have their default set (0, false, etc).
  • For enum types, values will be initialized to their first (0 value) field unless you have manually assigned values to the enum labels, in which case the value will still be 0 and might be invalid.

Upvotes: 1

Tal
Tal

Reputation: 439

It does not call the constructor just initializes with the default value. Keep in mind that it is also relevant for value types such as int, double and structs. Another use case is default a generic type. Each type has a predetermined default value which specified at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table

Upvotes: 1

Samvel Petrosov
Samvel Petrosov

Reputation: 7706

Here is how default works:

return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullable<T>, which is initialized like any struct.

new operator just creates new instance of the class and initialize properties/fields as it's written in the constructor.

Used to create objects and invoke constructors.

Upvotes: 6

D&#225;vid Florek
D&#225;vid Florek

Reputation: 571

According to documentation, default sets the variable to its default value. That means nullable types will be set to null, numeric types set to 0.

Upvotes: 2

Related Questions