Archive for July 2011

The myth of misusage of the var keyword since C# 3.0

C# 3.0 introduced a new keyword, var. The var keyword allows you to utilize type inference at compile time which is a really cool feature. Here’s an extremely basic example.

var message = "Hello World";

This should be self-explanatory: The compiler will resolve the local variable ‘message’ to be of type ‘string’, which is inferred by the value in the assignment statement. This is pretty cool, but it was never meant to change the C# specification or rid of using strongly typed names. The optimal usage of the var keyword is when you are dealing with Anonymous Types, and Generics. It was actually introduced along with the release of Linq in C# 3.0 which deals with these two language features quite often.

There are other scenarios where var is useful though, take this statement:

List<KeyValuePair<AccountRoles[], ToolStripMenuItem>> m_GuardedMenuItems = new List<KeyValuePair<AccountRoles[], ToolStripMenuItem>>();

That is a pretty knarly declaration and assignment statement, and this is a scenario where the var keyword would actually be recommended to improve readability to:

var m_GuardedMenuItems = new List<KeyValuePair<AccountRoles[], ToolStripMenuItem>>();

This also benefits the language outside the scope of the compiler. You can easily see that the first sample causes the syntax highlighter on this page to have to scroll – so for programming books, reference material, and blogs like this var has its use outside the realm of actual C# programs.

Bad: When the type is not obvious.

var doc = Factory.GetDocument(); // What is doc?

Good: When the type is obvious.

var text = new StringBuilder(); // We easily can see it is inferred to StringBuilder

The truth is, you can come up with more good examples of when to use var, then when not to use it. Another example would be refactoring. Say you have the following.

List<Order> orders = Factory.GetOrders();

Later down the road if the return type of Factory.GetOrders() were to change, you would have to go refactor every declaration that uses that method. However with var, you would not have had to done this if you used var in the first place.

var is pretty controversial, but the general consensus from the experts is its not as bad as everyone thinks.

Dangers of the public access modifier.

Did you know that the public access modifer in C# is essentially the equivalent to extern in C++? According to the C# 4.0 language specification, it is.

People need to be careful with the public keyword. public in C# is not equivalent to public in C++! In C++, it means “internal to my compilation unit.” In C#, it means what extern meant in C++ (i.e., everybody can call it). This is a huge difference!

This was best said by Krzysztof Cwalina, quoted in the revised Fourth Edition of The C# Programming Language. It actually makes more sense to me know when I browse the .NET Framework source code as to why I see Microsoft using internal access modifiers quite a bit more often. If you are rusty and don’t quite remember the access modifiers they are:

public
Access not limited.

protected
Access limited to this class or classes derived from this class.

internal
Access limited to this program.

protected internal
Access limited to this program or classes derived from this class.

private
Access limited to this class.

But remember, as Christian Nagel said it best, that internal is rather best described as being “access limited to this assembly”, because a program can be defined as a collection of executables and assemblies, and a class marked as internal cannot be accessed by an assembly referencing it.

Why abstraction can be detrimental.

The other day someone asked a question about the relation between the Socket class, and the UdpClient class. Specifically, what is the relation? While the answer is simple because UdpClient is merely wrapper around a UDP initialized socket, this also lead me to thinking more about abstraction.

So what is abstraction?
Take the following code sample.

XDocument xdoc = XDocument.Load(ConfigurationFilePath);
string boolstr = xdoc
    .Element("ApplicationConfiguration")
        .Element("Settings")
            .Element("AutoLogin")
            .Attribute("Enabled")
            .Value;
return boolstr.Equals(Boolean.TrueString, StringComparison.OrdinalIgnoreCase);

Imagine if you had to write that every time you wanted to retrieve a value in a configurationfile. That’s a lot of replicated code. In it’s simplist form, a C# Property is a form of abstraction – it hides the underlying implementation. Functions can also be considered abstraction. So, in essence we could do the following.

/// <summary>
/// Gets or sets a System.Boolean value indicating whether automatic login is enabled
/// </summary>
public static bool AutoLoginEnabled {
    get {
        XDocument xdoc = XDocument.Load(ConfigurationFilePath);
        string boolstr = xdoc
            .Element("ApplicationConfiguration")
                .Element("Settings")
                    .Element("AutoLogin")
                    .Attribute("Enabled")
                    .Value;
        return boolstr.Equals(Boolean.TrueString, StringComparison.OrdinalIgnoreCase);
    }
    set {
        XDocument xdoc = XDocument.Load(ConfigurationFilePath);
        xdoc.Element("ApplicationConfiguration")
                .Element("Settings")
                    .Element("AutoLogin")
                    .Attribute("Enabled")
                    .Value = value ? Boolean.TrueString : Boolean.FalseString;
        xdoc.Save(ConfigurationFilePath);
    }
}

So what happened here? We took a segment of code and wrapped in a C# Property, hiding the underlying implementation. This is called abstraction. So now we can easily just call SomeClass.AutoLoginEnabled = true, and the Property takes care of the dirty work underneath. Now this is obviously a very basic concept of abstraction. Generally, real-world abstraction in program code means asbtracting base classes, services, and other really complex things, but the idea here to understand the basic concept of abstraction.

How this relates to UdpClient and Socket
I always thought the Socket class was easy enough, but I often find that quite a few people prefer to use UdpClient or TcpClient, because they feel that it is easier to work with. This may be the case, but even the Socket class is a layer of abstraction as it is a wrapper around the Berkeley socket interface.

C# makes abstraction easy to do. It’s plain and simple. The reason this is dangerous though, is because often times developers create so many layers of abstraction, that it is often hard for either Jr. Developers or new people to the code to learn what is going on. I often find that many beginners in programming can understand the fundamentals of the code they are using. So in this case a beginner programmer may learn the UdpClient class inside-and-out, but in the end, they may not have a single clue about how that class is actually implemented, what goes on underneath, and how network programming is actually done.

In short, absraction is a good thing – when you also take the time to learn and understand the underlying implementations. However, you can definitely see how this can act negatively on a developer’s understanding of program code.

What to expect.

I finally decided to start a blog. My goal is to simply write about C# and Microsoft .NET specifically, and real-world programming problems. I will try not to venture outside that realm unless it is directly related to the topic at hand. I really love the C# programming language and I think .NET is a great technology and I enjoy talking about it.