using System.Collections.Generic;
public static void Main()
var xx = new List<int>{1};
var yy = new List<int?>{};
var zz = new List<int?>{1};
Console.WriteLine(GetValueFromList<int>(xx));
Console.WriteLine(GetValueFromList<long>(xx));
Console.WriteLine(GetValueFromList<int?>(xx));
Console.WriteLine(GetValueFromList<long?>(xx));
Console.WriteLine(GetValueFromList<int>(yy));
Console.WriteLine(GetValueFromList<long>(yy));
Console.WriteLine(GetValueFromList<int?>(yy));
Console.WriteLine(GetValueFromList<long?>(yy));
Console.WriteLine(GetValueFromList<int>(zz));
Console.WriteLine(GetValueFromList<long>(zz));
Console.WriteLine(GetValueFromList<int?>(zz));
Console.WriteLine(GetValueFromList<long?>(zz));
public static T GetValue<T>(object value)
if (value == null || value == DBNull.Value)
if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>)) {
return (T) Convert.ChangeType(value, Nullable.GetUnderlyingType(typeof(T)));
return (T) Convert.ChangeType(value, typeof(T));
public static T GetValueFromList<T>(dynamic values)
if (values == null || values.Count == 0) return default(T);
if (values.Count > 1) throw new ArgumentException("values must contain a single value", "values");
return GetValue<T>(values[0]);