1 - Nullable Types in C#
We can't initialize a variable to null, because null itself isn't a value of the same type.
Simply put, we can't do the following:
int enteroNulo = null;
note: in our example we use an integer, but it can be any data type, like decimal or datetime
However, C# lets us handle this by allowing us to modify the types so that they are nullable. This is done by adding the ?
character after the type.
int? enteroNulo = null;
enteroNulo =123;
As you can see, it lets us have an integer that is null
, and we can assign it a value without any problem.
But if we want to assign this value to a variable that is an ordinary integer, it will give us an error.
int enteroNormal = 234;
int? enteroNulo = 123;
enteroNormal = enteroNulo;
This makes sense since they are not the same type; int?
can contain a null value, while int cannot. To perform that conversion, we need to use one of its properties.
1.1 - Properties of Nullable Types
Nullable types let us access certain properties that make it easy to perform the actions we need. For example, the HasValue
property tells us whether it contains a value or is null. And finally, the Value
property gives us the variable's value if it isn't null.
So, based on the previous example, we could check if the variable enteroNulo has a value and, if it doesn't, assign it.
if(enteroNulo.HasValue())
{
enteroNormal = enteronulo.Value;
}
If there is any problem you can add a comment bellow or contact me in the website's contact form