Reputation: 3469
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 :
default(foo);
?foo obj1 = default(foo);
equal the foo obj1 = null
?Thanks in advance.
Upvotes: 2
Views: 789
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.
int
and bool
the value returned would be 0
or false
respectively.null
, even if they cannot normally be null
because of a constructor! Value fields will have their default set (0
, false
, etc).Upvotes: 1
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
Reputation: 7706
Here is how default
works:
return
null
for reference types andzero
for numeric value types. Forstructs
, it will return each member of thestruct
initialized tozero
ornull
depending on whether they are value or reference types. Fornullable
value types, default returns aSystem.Nullable<T>
, which is initialized like anystruct
.
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
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