for instance, if I have this code:
if (foo != default(foo))
{
int foo2 = foo;
}
is there a way to shorten this to only the assignment? in pseudocode, something like:
foo2 = if not default foo
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The problem with trying to shorten this is that
foo2is only valid within the scope inside your if statement. By moving this into one line, you’d always have to havefoo2defined in the outer scope, and it would always need some value.If that is acceptable, you could use C#’s conditional operator:
Note that you need something for when
foo == default(foo), as well, which becomes the final portion. With an int value, I would probably use: 0;at the end, but since you’re checking againstdefault(foo), I’m assuming your “real use case” is probably not anInt32value…Edit:
Given this comment, you could do:
This would effectively reassign
foo2iffoodoesn’t have it’s default value, and leave it alone (assign it to itself) if it does.That being said, I personally prefer something similar to your original:
This is, in my opinion, far more clear in terms of your intent, and does avoid the extra assignment to yourself that you’re getting with a conditional operator.