Skip to content

Instantly share code, notes, and snippets.

@cerkit
Last active March 28, 2016 22:17
Show Gist options
  • Save cerkit/15e6ef7f4f877795b633 to your computer and use it in GitHub Desktop.
Save cerkit/15e6ef7f4f877795b633 to your computer and use it in GitHub Desktop.
I have a dilemma. Should I use line 4, 8, 12, or 16?
// Dilemma, should I use this code:
// NOTE: existingJobDetail.Id is defined as a regular (non-nullable) int.
int? parentJobDetailId = existingJobDetail != null ? existingJobDetail.Id as int? : null;
// Or this code:
int? parentJobDetailId = existingJobDetail != null ? (int?)existingJobDetail.Id : null;
// Or (less likely):
int? parentJobDetailId = existingJobDetail != null ? existingJobDetail.Id as Nullable<int>: null;
// Or:
int? parentJobDetailId = existingJobDetail != null ? (Nullable<int>)existingJobDetail.Id : null;
@KeithJRome
Copy link

The first pair is identical to the second pair. int? is just an alias for Nullable<int>.

The as casting might work, but straight casting is more appropriate. as is intended for polymorphic casting, such as when accessing an explicit interface implementation or when attempting to upcast a reference type to a more concrete type and the cast isn't guaranteed to succeed. In this case, Nullable<T> is a value type (struct) and so is your base data type (int), and there exists both explicit and implicit conversion operators. Additionally, as probing carries additional overhead although I am not certain whether the compiler will recognize that existingJobDetail.Id as int? will never return null. If it does recognize that, then I would imagine it would treat the two forms the same as far as emitted IL is concerned.

So I would use the form of your second example:

int? parentJobDetailId = existingJobDetail != null ? (int?)existingJobDetail.Id : null;

@darronj
Copy link

darronj commented Mar 28, 2016

I'd probably put a sanity check around the statement, like the following since the parentJobDetailId can be null.

if(existingJobDetail != null){ parentJobDetailId.Value = existringJobDetail.Id; }

It's not as terse, but it is more readable and that's a trade off I like to make.

@darronj
Copy link

darronj commented Mar 28, 2016

scratch that, if this is the most current c#, I'd do the following.

int? parentJobDetailId = existingJobDetail?.Id ?? null;

@PaulLockwood
Copy link

Can you not just create a new nullable variable do a SetValue? I don't have a C# compiler handy + have done very little C# for quite a while.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment