Default literal and non nullable reference types
Hi there
I create this post to chat about the default literal.
How come that the default literal for every non nullable reference type is null ?
At the root, I see that the line "object obj = default;" makes variable "obj" have "null" in it.
Same for a string or for a custom Type (a class) that I instantiate.
I found this topic : https://stackoverflow.com/questions/63596203/non-nullable-reference-types-default-values-vs-non-nullable-value-types-defaul
And the accepted answer mentions this :
Would it be correct to say that, from a beginner perspective, it would be easier to have the default value of any non nullable reference type set to the default constructor of that type (to avoid null values in code), BUT that it is not like that in C# for practical reasons linked to the performance of C# and its Runtime ?
My questions are the following :
I create this post to chat about the default literal.
How come that the default literal for every non nullable reference type is null ?
At the root, I see that the line "object obj = default;" makes variable "obj" have "null" in it.
Same for a string or for a custom Type (a class) that I instantiate.
I found this topic : https://stackoverflow.com/questions/63596203/non-nullable-reference-types-default-values-vs-non-nullable-value-types-defaul
And the accepted answer mentions this :
This makes sense from a practical standpoint, as one of the basic usages of defaults is when declaring a new array of values of a given type. Thanks to this definition, the runtime can just zero all the bits in the allocated array - default constructors for value types are always all-zero values in all fields and null is represented as an all-zero reference.Would it be correct to say that, from a beginner perspective, it would be easier to have the default value of any non nullable reference type set to the default constructor of that type (to avoid null values in code), BUT that it is not like that in C# for practical reasons linked to the performance of C# and its Runtime ?
- Is the default literal equal to "null" because the runtime would have to use more memory than it really needs, for every class instantiation, if it was something else ? (I am not sure that I have understood the StackOverflow answer)
- When do you guys use the "default" literal ? Do you have an example ?
Stack Overflow
This isn't my first question about nullable reference types as it's been few months I'm experiencing with it. But the more I'm experiencing it, the more I'm confused and the less I see the value ad...