Tuesday, December 28, 2010

C# equivalent of Python pass statement

I'm coding an extension method today, I encounter again the empty statement pattern.

I wanted to write Assert.Success() on successful condition, but alas, there's no Assert.Success(), we only have Assert.Fail() and Assert.Ignore().

So I am compelled to write this:

public static class Helper
  public static void AssertContainsMessage(this string message, string messagePortion)
   if (message.Contains(messagePortion))
    Assert.AreEqual(message, messagePortion);

However, the compiler balk at the notion that my semicolon code is possibly a mistaken empty statement.

Python has a pass statement...
if i != 0:
        print 'please check your parameters'

..., and I wish C# allows this explicit intent of an empty statement:

if (i != 0)
    Console.WriteLine("please check your parameters");

That null == empty right? null statement == empty statement. But that is not palatable to most C-based programmers.

So we have to get by with using a block with no statements, this works:

if (i != 0)
    Console.WriteLine("please check your parameters");

Hmmm.. :-) There's no more compiler warning. Typing curly braces requires a more conscious effort, an intent, hence the compiler rationale for not raising a warning; whereas a semicolon, is a second nature on all C-based programmers. Perhaps the best analogy could be is like most people, when they want to click something, they perform double-click, regardless if it is needed or not, it's not a conscious effort, most users just double click. And most C-based programmers just terminate anything with a semicolon.

One time or another, you have mistakenly write a property with semicolon...

public class Person
    public int PersonId { get; set; };

..., only to quickly backspace that obnoxious semicolon after of closing bracket, how unforgiving compiler!

I digress, just think if the compiler will not balk on empty statement:

if (ans == 'Y');

Advice for morts, heed compiler warnings :-)

No comments:

Post a Comment