Archive

Posts Tagged ‘c-sharp’

Bad Programming Examples in C#

February 23, 2009 msujaws Leave a comment

I’m starting to compile a list of constructs I’ve seen in production C# code that needs to be modified. Code Analysis will flag most of these. Here is the first of them, with more to be added later:

1. Never leave a blank catch statement or use catch(Exception)

In C#, if you write catch(Exception) or a blank catch, the exception will be casted to a System.Object. This will also catch non-CLS compliant exceptions. If you can’t do anything to remedy the exceptional situation, you shouldn’t be catching the exception. Usually when you see a code construct like this, the exception is rethrown. Not only is this unnecessary and bad programming, it ruins the stack trace and any other important information that Windows Error Reporting can provide for you.

If you are unsure what type of exception can be thrown, you should check the documentation. If you are catching the exception so that you can perform some cleanup before exiting, then you should move that cleanup code to a finally block. If the latter is the case, then you probably don’t need the catch block there in the first place.

If you run Code Analysis on your code, you will receive a CatchNonClsCompliantExceptionsInGeneralHandlers warning.

More information can be found about why not to have empty catches in your code at the CLR Team Blog.

Stepping in to .Net source code with VS2008 SP1

January 31, 2009 msujaws Leave a comment

With the release of Visual Studio 2008 SP1, a new feature was introduced and touted, but not turned on by default. This feature allows you to step in the .Net source code while debugging in Visual Studio. If at any point within your code, you can look at the callstack and traverse all the way down to the creation of the current running thread. Very cool!

To do this, you just have to change a couple default options.

First, go to Tools -> Options. Choose “Debugging” from the left-hand side menu, and uncheck the Just-my-code option. Next you’ll want to check “Enable .Net framework source stepping”.

Hit OK, and the symbols should* start to download from Microsoft’s servers, complete with developer comments.

The first time view the code you will be prompted to accept their license agreement.

*If the symbols didn’t download when you hit OK, you can go to the Symbols submenu and choose to download the symbols explicitly from the Microsoft servers. I’ve noticed this happening on a coworker’s machine once already.

The coalesce operator, BKA the double question marks

January 13, 2009 msujaws 2 comments

In C#, there is a nice little operator that is rarely used. I’m not sure if this is because most people haven’t heard of it before or they just don’t know how to use it.

Basically, this operator allows you to check if a object is null, and if it is, return a different object.

Use this:

return userName ?? string.Empty;

Instead of this:

return (userName != null) ? userName : string.Empty;

Pretty simple, and it will save some typing. I’ve heard arguments against using the ternary operator from people claiming not to use it because fellow developers wouldn’t know what it is. That’s not the mindset we should have. If an operator exists in a language and there is a perfectly valid use for it, then go ahead and use it. When your colleage sees it, they will learn something about the language they never knew before and will most likely appreciate it.

Categories: Uncategorized Tags: , ,

Finally will execute, even after return

January 7, 2009 msujaws Leave a comment

How’s this for weird looking code?

public static void RunSnippet()
{
    var y = testFinally();
    if( y == 99 )
    {
        WL("It is 99");
    }
    else
    {
        WL("It is 6");
    }
}

public static int? testFinally()
{
    int? x = 99;
    try
    {
        return x;
    }
    finally
    {
        x = 6;   
    }
    return x;
}

What happens? testFinally will return 99. If you changed the finally block to set x equal to null, the same result will happen. When there is a finally block, the function will not return until after the finally block has finished, regardless of any code following it. The second return statement is never reached. Also, you cannot return from a finally block, since control flow statements cannot be made in a finally block.

The code above was written with SnippetCompiler, a really nice free tool to have at your side when you want to test something out but don’t want to create a new solution in Visual Studio.

Categories: Will It Compile? Tags: ,

Extension Methods on Null Instances

January 6, 2009 msujaws 1 comment

I was reading some blog posts and came across one from Brad Wilson about a year ago. Extension methods are a pretty cool construct, allowing you to add instance methods to sealed classes easily. This brings with it a way to write code that can cause some weird readability issues. Often used is the static method String.IsNullOrEmpty. With an extension method you could add that method to instances and the code will work fine, even if the object is null.

Here’s a code sample:

using System;

public static class MyExtensions
{
   public static bool IsNullOrEmpty(this string str)
   {
      return String.IsNullOrEmpty(str);
   }
}

Now all Strings will have a method to check if they are null or empty. You can see that the readability would make you think that a NullReferenceException would be thrown if the object is null and the method wouldn’t get called. This is the odd part of extension methods.

The method will still get called, and the code will work like normal.

public static void Main()
{
   string str = null;
   bool strIsNull = str.IsNullOrEmpty();
   System.Console.WriteLine(strIsNull);
}