Implement string properties
1, public string Prop { get; set} = string.Empty;
2, public string Prop { get; set} = "";
3, public string Prop { get; set} = default!;
Hi, I am a newbie, could some one help me to have better understand use case of those 3 way implement string properties above ? ( especially 3rd way)
Thanks in advanced!
13 Replies
The first two are equivalent, they use an empty string as the default value
The last makes it
null
instead of an empty string, and since you're using !
it looks like you are using nullable reference types, and since you're storing null into a property that states it isn't null you are potentially going to cause issues
If you wanted to allow Prop
to have a null value, use string?
instead of string
, and then you can remove the !
Is 3rd way is wrong way or could have some design intended?
the default value is null for reference types
it's redundant
this
and this
are both null
they are the same
Henkypenky#4865
REPL Result: Success
Console Output
Compile: 644.741ms | Execution: 96.305ms | React with ❌ to remove this embed.
C# always had nulls
but now you get more help to deal with them
in your case
if you don't use the null forgiving
!
it will shout at youthis means
in a NON NRT world
so it's just for bypass waring right?
when an instance is created it must contain a value, because the default constructor will initialize as null
but in NRT world
if you mark it as nullable
it doesn't matter
the compiler knows you said: hey this can be null, chill out
yes, it's called the null forgiving operator
I highly discourage you from using it
yeah im across some internet code sample, just want get a better understand of it
Whether you use:
-
string
and string.Empty
- string?
and null
- string
and the required
keyword
- string
and initialise it in the constructor
Depends on what values you want the property to hold and how you want it to be set the first timeMarko Hrnčić
Code Maze
Realistic Data Generation in .NET With Bogus - Code Maze
Learn how to generate realistic data with the Bogus .NET library and save your time when mocking data and seeding databases with EF Core
Bogus is really god
good