✅ Purpose of '?' key when declaring certain fields.
I am curious, what is the "?" symbol used for in C# in the following context. Note, I am getting this example from C#11 and .NET 7 Modern Cross-Platform Fundamentals by Mark J. Price.
For example, lets say I have a public class:
public class Person
{
public string? Name;
public DateTime DateOfBirth;
}
what exactly is the '?' keyword doing? I know in other languages the '?' keyword can be used to verify if your intialization does match what you are expecting: "Check if Name is a String. Throw an exception if not."
I do not understand why the string class would need this? DateTime is also checking for the correct datatype, yet I do not see it being addded. I do not understand what would make string special. Is the '?' symbol doing something else? Why does the author feel the need to add this step?
8 Replies
Lamo. Thanks!
it was a feature introduced in C#8, and I believe is still opt-in
at least, half of it was introduced in C#8
it can mean 2 different things
this is actually shorthand for
and has been around since like... C#4?
maybe 5?
and doesn't need any settings or anything,
Nullable<int>
and int
are distinctly different types
actually compiles to (not completely sure of the names)
so, string
and string?
are actually the exact same
string?
is not a real type, but it's a language annotation that the compiler can use to do null checking analysis
I.E. if you TELL the compiler that Name
is intended to sometimes be null, it can generate better warnings for when you're not doing null checking
alternatively, if you specify just string
to indicate that it's NOT ever intended to be null, it can warn you when you forget to initialize it, do any other operation that would maybe allow it to be null
this is all static analysis, though, so it's not a perfect system, but it's a significant improvement, built on the existing architecture of C# and .NETYou're kinda right, but I wouldn't use any attributes in such an explanation. They're just confusing, since
MaybeNull
is an actual attribute that is not used hereright, which is why I clarified that I wasn't sure of the naming
or is that scenario not attribute-based at all?
The encoding is an extremely complicated compression algorithm that depends on a large number of factors
I would avoid talking about it at all
Yes, its very important to show that there is a big difference between nullable value vs nullable reference types. One id actually there at runtime the other one isn’t.
That isn't what I said. I said avoid using attributes to talk about it
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.