I prefer not to cast null
value (it looks odd to me):
long? variable1 = reader.IsDBNull(2) ? null : (long?)reader.GetInt64(2);
Another options:
long? variable1 = reader.IsDBNull(2) ? default : reader.GetInt64(2); // requires C# 7.1
long? variable1 = reader.IsDBNull(2) ? default(long?) : reader.GetInt64(2);
long? variable1 = reader.IsDBNull(2) ? (long?)null : reader.GetInt64(2);
long? variable1 = reader.IsDBNull(2) ? new Nullable<long>() : reader.GetInt64(2);
long? variable1 = reader.IsDBNull(2) ? new long?() : reader.GetInt64(2);
long? variable1 = reader.IsDBNull(2) ? null : new long?(reader.GetInt64(2));
It's just the matter of taste. I think first option is more readable, than others.
UPDATE: Consider also writing some extension methods to make your code more clear:
public static class DataReaderExtensions
{
public static long? GetNullableInt64(this IDataReader reader, int index)
{
if (reader.IsDBNull(index))
return null;
return reader.GetInt64(index);
}
}
In this case you don't use ternary operator (no casting to nullable), and reading values from reader looks more pretty:
long? variable1 = reader.GetNullableInt64(2);