質問

if (msg.Body.Contains("logging"))
{
    enableLogs = !enableLogs;
    sendMsg(enableLogs == true ? "Logging enabled." : "Logging disabled.");
}
else if (msg.Body.Contains("afk"))
{

}

How would I go about turning this into a ternary if statement? It's not necessary if it won't work out nice, trying to make my program cleaner.

役に立ちましたか?

解決

Ternary statements are strictly for assignments, not for else-if or multi-decision logic. It would only work if both logic paths returned an instance of a type. :)

var result = booleanValue ? logicPathForTrue : logicPathForFalse;

A "good" (academic) use of ternary:

// Assign something to result. If something is null, assign new Something to result
Something result = something == null ? new Something() : something;

Ternary operations require variable assignment. This compiles:

var something = true ? new object() : null;

This does not compile:

true ? new object() : null;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top