19 Replies
should I use required attribute?
can I just do:
public required string Identity {get;set;}
strings are nullable by default. Within a nullable context
= null!
indicates that the string value should be initialized
If you are familiar with nullable value types int?
for example it indicates that the int can be null.
string is a reference type and it is therefore possible that the value could be null (no reference). You could think of it as every string
is a string?
https://stackoverflow.com/questions/54724304/what-does-null-statement-mean for a much better written explanation 😁
As for best practice i am not sure, but if you have nullable enabled on the project and you want to indicate the string should not be null then i'd imagine it is correct but YMMV on what people do out in the wild ~It just shuts up the compiler about the property not being initialized in the constructor
So it initializes it with
null
but also says "trust me bro, it's not null"
And, yes required
is the preferable way nowadaysDoes required also shut it up? I thought it was more for binding shenanigans?
It does, yes
Because it enforces the property to be set
Makes sense i guess, i didn't think the component model stuff interacted with the nullability stuff but it's nice that it does
[Required]
attribute is not the same as required
keyword
The former does nothingWe have a required keyword??
The latter enforces the property to be set
Yes
Angius
REPL Result: Failure
Exception: CompilationErrorException
Compile: 266.582ms | Execution: 0.000ms | React with ❌ to remove this embed.
Oh C#11, dang i'm fallin behind
Angius
REPL Result: Success
Compile: 300.918ms | Execution: 38.861ms | React with ❌ to remove this embed.
Oh i understand you, you mean it's preferable to use the reuqired keyword
I thought you were talking about the attr 😂
Yeah
Oh but it also kills the
new()
constraint that's a little restrictive
I mean probably fine and correct, but does limit you for some stuffI mean, it does enforce the property to be set
You cannot create an object without the property being set
you can still activator it right?
If it allowed you to just
new()
up the object without setting the property... wouldn't make much sense, would it
I mean, I guess? If you want to use reflections to break the correctness of your code lolAlways 🙂