Last active
March 28, 2016 22:17
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
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.
scratch that, if this is the most current c#, I'd do the following.
int? parentJobDetailId = existingJobDetail?.Id ?? null;
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
The first pair is identical to the second pair.
int?
is just an alias forNullable<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 thatexistingJobDetail.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: