Reputation: 2305
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
Upvotes: 0
Views: 107
Reputation: 1
You can also do something like this:
foo2 = foo != default(foo) ? foo : foo2;
Upvotes: 0
Reputation: 564363
The problem with trying to shorten this is that foo2
is only valid within the scope inside your if statement. By moving this into one line, you'd always have to have foo2
defined in the outer scope, and it would always need some value.
If that is acceptable, you could use C#'s conditional operator:
int foo2 = foo != default(foo) ? foo : default(int);
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 against default(foo)
, I'm assuming your "real use case" is probably not an Int32
value...
Edit:
The (int) was an afterthought, in what I was actually trying I already had foo2 assigned so this is exactly what I was looking for.
Given this comment, you could do:
foo2 = foo != default(foo) ? foo : foo2;
This would effectively reassign foo2
if foo
doesn'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:
// Assumes foo2 is already defined, based on your comment
if (foo != default(foo))
foo2 = foo;
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.
Upvotes: 5
Reputation: 203814
You aren't going to be able to simplify that any more than you have. If you were just setting the value of foo2
rather than declaring it (and in a scope block as well) then you could conceivably refactor it into a method for a tiny gain.
Upvotes: 0
Reputation: 51634
// either
int foo2 = (foo != default(foo)) ? foo : default(int);
// or
int? foo2 = (foo != default(foo)) ? foo : null;
Upvotes: 0