I use Nullable<T>
types quite a lot when loading values into classes and structs when I need them to be nullable, such as loading a nullable value from a database (as the example below).
Consider this snippet of code:
public class InfoObject
{
public int? UserID { get; set; }
}
// Load the ID into an SqlInt32
SqlInt32 userID = reader.GetSqlInt32(reader.GetOrdinal("intUserID"));
When I need to load a value into a nullable property, sometimes I do this:
infoObject.UserID = userID.IsNull ? (int?)null : userID.Value;
Sometimes I do this instead:
infoObject.UserID = userID.IsNull ? new int?() : userID.Value;
Although they achieve the same result, I'd like to see if anyone knows which is better to use between (int?)null
and new int?()
with regards to performance, smallest IL code, best practices etc.?
Generally I've been favouring the new int?()
version of the code above, but I'm not sure whether casting (int?)null
is quicker for the compiler to resolve than new int?()
.
Cheers!