Nullable types and ?? operator C# [en-US]

Nullable types vs Non-nullable types

 

While developing our C# projects its frequent the null comparison operation to avoid null exceptions. This simple operation is mainly coded using the “var x = null” code example inside an if clause. However not all types of variables are nullable, which means that setting a variable to null is not allowed in every cases, it depends on what kind of type are you defining. But what if there was an extension to your non-nullable type that would convert your variable types to nullable? This extension really exists.

As I said before in C# you have nullable types which represent all the values of an underlying type, and an additional null value and can be declared easily using “T?”, where T is the type of the variable and for example the normal int type cannot be null, so its a non-nullable type, however if you define a “int?” your variable can be null, what you do is convert a non-nullable type to a nullable type.

Example:

int x=null;     Not allowed

 

image

 

int? x=null;   Allowed

 

image

 

While using nullable types you can check if a variable is null the same way you do it with nullable types:

 

image

 

But what about setting a default value when a certain variable is null?

In this cases the c# .net framework let you set a default value when you try to assign a nullable type to a non-nullable type, using the ?? operator.

If you don’t use this operator you can still catch the InvalidOperationException which is throw in this cases.

For example  without the ?? operator :

image

Using the ?? operator your code becomes cleaner and more easy to read and you get a bonus, you can set a default value for multiple variables using the ?? in a chain set.

image

That’s it,

Thanks, Rui Machado

rpmachado.wordpress.com

Anúncios

Deixe uma Resposta

Preencha os seus detalhes abaixo ou clique num ícone para iniciar sessão:

Logótipo da WordPress.com

Está a comentar usando a sua conta WordPress.com Terminar Sessão / Alterar )

Imagem do Twitter

Está a comentar usando a sua conta Twitter Terminar Sessão / Alterar )

Facebook photo

Está a comentar usando a sua conta Facebook Terminar Sessão / Alterar )

Google+ photo

Está a comentar usando a sua conta Google+ Terminar Sessão / Alterar )

Connecting to %s