Similar to Pass in Python for C#

Viewed 26939

In python we can ...

a = 5
if a == 5:
    pass #Do Nothing
else:
    print "Hello World"

Is there a similar way to do this in C#?

8 Answers

Use empty braces.

int a = 5;
if (a == 5) {}
else {
  Console.Write("Hello World");
}

Why not just say:

if (a != 5) 
{
   Console.Write("Hello World");
}

Is pass used in the context of a loop? If so, use the continue statement:

for (var i = 0; i < 10; ++i)
{
    if (i == 5)
    {
        continue;
    }

    Console.WriteLine("Hello World");
}

Either use an empty block as suggested in other answers, or reverse the condition:

if (a != 5)
{
    Console.WriteLine("Hello world");
}

or more mechanically:

if (!(a == 5))
{
    Console.WriteLine("Hello world");
}

A better question would be why you would want to do such a thing. If you're not planning on doing anything then leave it out, rather.

int a = 5;
if (a != 5) {
    Console.Write("Hello World");
}

Why make it easy when you could do it unnecessarily difficult?

((Action) (() => { }))();

On a serious note, the C# equivalent of the Python pass statement would be

;

since it's a line of code that does nothing. While

{}

would achieve the same result, you're actually creating a scope containing no lines of code.

Related