简体   繁体   中英

One-line if-else in C#

In C#, is there a one-line implementation of the following simple piece of logic ?

if (a != null) 
{
    b = a ;
}
else
{
    // do something else;
}

Notice that in the else I do not want to assign a different value to the variable b.

Maybe you were looking for braceless notation?

if (a != null) b = a; else /*Do something else*/ ;

Please, use this sparingly and make sure the oneliner will be readable.

不知道为什么要这样做,但这是我的看法:

((a != null) ? (Action)(() => { b = a; }) : () => { /*Do something else*/ })();

If you want to do an if / else in a single line, you must know the structure that the code must have:

condition ? consequent : alternative

For example:

string A = "test";
Console.WriteLine(String.IsNullOrEmpty(A) ? "Yes" : "No");
//Result = No

string B = "";
Console.WriteLine(String.IsNullOrEmpty(B) ? "Yes" : "No");
//Result = Yes

我真的不知道为什么,但是是的,您可以:

if (a != null) { b = a; } else { Console.WriteLine("Welcome to the 'else' branch"); }
string asd = "asd";
string bsd = null;

asd = bsd != null ? bsd : new Func<string>(() => { Console.WriteLine("Do something"); return asd; })();

This won't change asd and it is "one-liner" but i would not recommend this over normal if else

Easiest way is probably to do this:

b = a != null ? a : b;

Syntax for this is:

someValue = condition ? newValue : someOtherValue;

If you need it to something more specific when a is null then you can do this, but it's not pretty:

public static void Main()
{
    int? a = null;
    int b = 0;
    b = a != null ? a.Value : yeet(b);
    
    System.Console.WriteLine(b);
    
}

public static int yeet(int b){
    System.Console.WriteLine("yeet");
    return b;
}

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