Olá pessoal,
estive preparando um código muito bacana para verificar se um determinado tipo de objeto (type) aceita valores nulos ou não.
Esse código é especialmente útil para quem utiliza muita reflexão (reflection).
Vamos ao código:
/// <summary>
/// Verifica se um determinado tipo de objeto aceita
/// nulo (nullable)
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public bool IsNullable(Type type)
{
// Cria Objetos
bool result;
Type objGenericType;
// Verifica se o Tipo é Genérico
if (type.IsGenericType)
{
// Recupera a Definição do Tipo Genérico
objGenericType = type.GetGenericTypeDefinition();
// Verifica se Aceita Nulo
result = objGenericType.Equals(typeof (Nullable<>));
}
else if (type.IsClass) // É uma classe
{
result = true;
}
else // Não Genérico
{
result = false;
}
// Retorna
return result;
}
Para utilizar-lo é bem simples:
bool aceitaNulo = IsNullable(MEU TIPO);
Exemplos:
bool aceitaNulo1 = IsNullable(typeof (string)); // Sim (true) bool aceitaNulo2 = IsNullable(typeof (Int32)); // Não (false) bool aceitaNulo3 = IsNullable(typeof (Int32?)); // Sim (true)
Espero que tenham gostado.
Até o próximo ;)
Posts Relacionados:



November 18th, 2010 at 7:21 AM
[...] This post was mentioned on Twitter by .Net Max, Guilherme Bacellar. Guilherme Bacellar said: Verificando se um tipo de objeto aceita valores nulos: Olá pessoal, estive preparando um código muito bacana par… http://bit.ly/cHgPhV [...]