Nullable Types in C#

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;
}

 

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café