Understand if a property is nullable with C# and reflection

The framework .NET offers a series of classes in its System.Reflection namespace, that allows us to investigate inside a type, and understand a wide range of characteristics on the same type.

We can start from an istance to get its ancestor type and related specifics.

In this case, we would like to know if a property is nullable or not. A nullable type is a type that can be declared or assigned to null value.

But what is exactly a nullable type ?. Someone of you maybe haven’t heard it anymore. Follow this link and learn more about it.

For the scope of this post, we want to understand how to detect if a type is nullable.

Well, considering we have a class as the following:

public class MyClass

{

public int iNotNullable { get; set; }

public int? iNullable { get; set; }

}

 

we will be able to understand, starting from an instance of this class, what are the nullable properties present in related type, in this manner:

MyClass c = new MyClass ();

Type T = c.GetType();

PropertyInfo[] properties = T.GetProperties();

foreach (PropertyInfo pi in properties)

{


// this is the statement to detect if the property is nullable

bool bNullable = pi.PropertyType.IsGenericType &&

pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);

 

Console.WriteLine(“{0} is {1}nullable”, pi.Name, bNullable ? string.Empty : “not “);

}

 

That’s all.

Understand if a property is nullable with C# and reflection

Lascia un commento

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...