Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting (int?)null vs. new int?() - Which is better?

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!

like image 566
Codesleuth Avatar asked Feb 11 '10 10:02

Codesleuth


People also ask

What happens if you cast null to int?

In other words, null can be cast to Integer without a problem, but a null integer object cannot be converted to a value of type int.

Can an int be Nullable?

Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.

What does New int mean in C#?

new int[] means initialize an array object named arr and has a given number of elements,you can choose any number you want,but it will be of the type declared yet.

What is the default value of Nullable int c#?

The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .


1 Answers

They will generate the same IL. Use whichever you find easier to read.

When you talk about something being "quicker for the compiler to resolve" are you talking about micro-optimising your build times? I have no idea which would be faster there, but I doubt it will make a reliably-measurable difference for any significant body of code.

Personally I use null whenever I can do so with no ambiguity; I think I still generally prefer the cast to calling new, but it makes no real difference.

like image 175
Jon Skeet Avatar answered Sep 29 '22 02:09

Jon Skeet