PuddyBear
✅ 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?
23 replies