Is there a keyword to 'do nothing' in C#?
For example I want to use a ternary operator where one of the actions is to take no action:
officeDict.ContainsKey("0") ? DO NOTHING : officeDict.Add("0","")
Is there a keyword to 'do nothing' in C#?
For example I want to use a ternary operator where one of the actions is to take no action:
officeDict.ContainsKey("0") ? DO NOTHING : officeDict.Add("0","")
No, there is no such keyword. Besides, the ?: operator is not meant for deciding actions. It's meant for deciding values (or, more technically, value expressions).
You really, really want to use an if condition for this sort of decision-making instead:
if (!officeDict.ContainsKey("0"))
officeDict.Add("0", "");
As others have pointed out, using an if statement is far more idiomatic here.
But to answer what you ask, you can use lambdas and delegates:
// Bad code, do not use:
(officeDict.ContainsKey("0") ? (Action)(() => { }) : () => officeDict.Add("0", ""))();
Setting aside the fact that this is a bad idea, you actually can create a 'DoNothing' method using an attribute to conditionally emit the method call (note this relies on the convention that you don't #define a 'NEVER' condition.) Because of the ConditionalAttribute, calls to the method will not be emitted and you essentially have a 'nop' section of code.
[Conditional("NEVER")]
public void DoNothing()
{
}
Still, as several others have already pointed out, this is not recommended.
Why do you want to use a ternary operator, if you only want to do something in one of the cases ? Why don't you just invert the condition and use an if statement ?
if (!officeDict.ContainsKey("0"))
{
officeDict.Add("0","")
}
The ternary operator is for expressions, not statements.
You want an if statement.
Why not just use an if statement so the code looks like this:
if(!officeDict.ContainsKey("0"))
officeDict.Add("0","")
Why not write it with a simple if?
if (!officeDict.ContainsKey("0"))
officeDict.Add("0","")
It will be far more readable.
Why don't you just use an IF statement for this?
if(!officeDict.ContainsKey("0")) officeDict.Add("0","");
Use an if statement instead.
if (!officeDict.ContainsKey("0"))
{
officeDict.Add("0","")
}
Try this (grinns)
if (officeDict.ContainsKey("0"))
Thread.Sleep(1)
else
officeDict.Add("0","")