Tuesday, March 1, 2011

c# why cant a nullable int be assigned null as a value

Hi Everyone

Can someone explain to me why a nullable int cant be assigned the value of null e.g

int? accom = (accomStr == "noval" ? null  : Convert.ToInt32(accomStr));

What's wrong with that code?

Thanks

From stackoverflow
  • The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:

    int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));
    
    Joe R : It's interesting - you don't actually need the cast for Convert.ToInt32...
    Slace : It's because System.Int32 != System.Nullable
    David Radcliffe : Why does long? work without the cast?
    Harry Steinhilber : As Joe R said, my cast on the Convert.ToInt32() was not necessary. There is an implicit cast from int to int?. The cast on the null is necessary regardless of whether you use int? or long?. The other options is to cast only the Convert.ToInt32() to an int? or long? (as suggested by Will Dean) as this will make the null convertible to the nullable type. The issue is that there isn't an implicit cast from => int or from int => .
  • What Harry S stays is exactly right, but

    int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));
    

    would also do the trick. (We Resharper users can always spot each other in crowds...)

  • Another option is to use

    int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr);

    Ilike this one most..........

0 comments:

Post a Comment