ยฉ 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#โ€ข11mo agoโ€ข
89 replies
Filomeon

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 :
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.
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 ?

๐Ÿ˜… My questions are the following :

1. 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)
2. When do you guys use the "default" literal ? Do you have an example ?
Stack Overflow
Non-nullable reference types' default values VS non-nullable value ...
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...
Non-nullable reference types' default values VS non-nullable value ...
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources
Was this page helpful?

Similar Threads

Recent Announcements
Next page

Similar Threads

Donโ€™t understand nullable reference types
C#CC# / help
4y ago
โ” Generics and nullable types
C#CC# / help
3y ago
Null Literal and NUll reference problems
C#CC# / help
17mo ago
deserialize non-nullable
C#CC# / help
2y ago