简体   繁体   中英

Is there a way to shorten use of an if statement in an assignment?

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

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.

// either
int foo2 = (foo != default(foo)) ? foo : default(int);
// or
int? foo2 = (foo != default(foo)) ? foo : null;

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.

您还可以执行以下操作:

foo2 = foo != default(foo) ? foo : foo2; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM