Brendan Enrick

Daily Software Development

C# Generics vs C++ Templates

I regularly meet with a group of my college friends with whom I studied Computer Science. While at a great local bar we have plenty of interesting computer-related conversations. A lot of .NET developers probably spend most of their time discussing technical topics with other .NET developers. Our conversations are much more interesting because everyone there works with different languages and different types of technology. It really adds a lot to our discussions. So as has happened a few times, I mentioned C# Generics. As usual it sparked a conversation about how C# Generics are not as good as C++ Templates. As usual I agree with them. (Yes, I really do like C++ templates better than I like Generics in C#)

So I searched on MSDN, because I wanted to see what Microsoft cites as the key differences between C++ templates and C# Generics. I found this article explaining the differences between C++ templates and C# Generics. OK, I agree these are some important differences. It says on there specifically that they were not even trying to have as much functionality as templates. It is good that they said that, because the list of "differences" could be renamed "reasons why templates are better".

The list of reasons cites a bunch of differences in how they are able to be used. I still want to know the differences in the implementation of them. For that big important difference they have it separated from the nice list. Its in the paragraph of description. They mention one HUGE difference. As they say, "C# generic type substitutions are performed at runtime and generic type information is thereby preserved for instantiated objects." So what is the big deal you might say. There are good things and bad things here for generics.

Since templates are compiled at runtime, the compiler will figure out every version of the template it needs and will create the code for them. This is great because it gives optimal performance. Sure there is a bit more code, but it is nice to not have to create these methods at runtime. With C# Generics, the required code is created at runtime. Ok so that sounds pretty bad. It isn't really as bad as it sounds. Generics are implemented smartly, and because of this it isn't much of a performance issue. So at runtime our code will be created to handle the different types our generic can handle. What if we're going to have a bunch of types? If they're all value types then you could have a problem. It will actually create a completely new implementation of your code for every value type you use for the generic. If you're using a reference type it uses some cool tricks to point to the correct type, so it only has to have one reference type implementation. This means you'll have the performance hit once when you first need the generic on a reference type. Then it is a minimal hit each other time you need it.

Yes, I was a C++ programmer before I learned C#. I hope you enjoyed this post. I appreciate comments. I really like the ones which add something to the post, so if you've got extra information to add I encourage you do so. If I've made any mistakes in this, please let me know.

Unable to cast object of type 'Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection' to type 'Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection'

Earlier today I was trying to track down this error.

Unit Test Adapter threw exception: The type initializer for 'Microsoft.VisualStudio.TestTools.UnitTesting.TestConfiguration' threw an exception. Unable to cast object of type 'Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection' to type 'Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection'

I tried Googling for it, but I didn't find anything regarding this problem. I was pretty sure it was a VS 2008 upgrade issue, because it looks like it is a dll version issue. Since the two classes it is trying to cast between are the same class. So I must be using the wrong version of a dll and I not too long ago upgraded to VS 2008.

In the App.config file there is a config section defined like this.

<section name="microsoft.visualstudio.testtools" type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection, Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

All that needs to be changes is to change the 8 into a 9. Once you make that change all will work once again.

This will work for pretty much any version issue you run into which looks like this. It is funny because the two class names are the same. This is your signal that it is a version issue. The nice thing is that you usually just need to change an 8 into a 9.

I hope everyone is enjoying Visual Studio 2008. Have a great day!

Try Catch Performance in CSharp: A Simple Test Response

I read an interesting little post about a Try Except Performance Test Using Python written by Patrick Altman. As he mentioned, I have also had discussions with people about this exact topic in the past plenty of times. He was testing the performance issue of whether it is better to use a try catch block to handle possible errors or to check for them before they're a problem.

He handled 2 different cases; the success and the failure. Using loops he performed time checks on these to see how long it took. I thought it was very interesting, but the nice question is how does this hold up using C#. So I also wrote a simple little test similar to his. The results are pretty interesting. Keep in mind this just gives some rough estimates on this.

 

The case where the key does not exist:
1,000 iterations:
Try_NotExist(1000) = 00:00:00.0852580
Without_Try_NotExist(1000) = 00:00:00.0000089
Without_Try_NotExist_Not(1000) = 00:00:00.0000089
100,000 iterations:
Try_NotExist(100000) = 00:00:06.1590461
Without_Try_NotExist(100000) = 00:00:00.0006802
Without_Try_NotExist_Not(100000) = 00:00:00.0006799
1,000,000 iterations:
Try_NotExist(1000000) = 00:01:02.8172468
Without_Try_NotExist(1000000) = 00:00:00.0070592
Without_Try_NotExist_Not(1000000) = 00:00:00.0092609

The case where the key does exist:
1,000 iterations:
Try_Exist(1000) = 00:00:00.0000083
Without_Try_Exist(1000) = 00:00:00.0000117
Without_Try_Exist_Not(1000) = 00:00:00.0000117
100,000 iterations:
Try_Exist(100000) = 00:00:00.0006185
Without_Try_Exist(100000) = 00:00:00.0008624
Without_Try_Exist_Not(100000) = 00:00:00.0008492
1,000,000 iterations:
Try_Exist(1000000) = 00:00:00.0088896
Without_Try_Exist(1000000) = 00:00:00.0086661
Without_Try_Exist_Not(1000000) = 00:00:00.0097892

As you can see here my results are somewhat similar to the findings Patrick found. If it is going to fail often at all you're much better off checking for the error before it fails because of how immense the difference between handling the error and not is. However if pretty much every time the code will succeed without any errors, you're better off with the try-catch block by a very small amount. The fact that it is only a small amount better tells me that I am much better off checking for an error than I am using a try-catch block to trap the error.

And so you can try for yourself or inform me of any errors I've made I'll include my code.

using System;
using System.Diagnostics;
using System.Text;

namespace Try_Catch_Performance
{
    class Program
    {
        private static int[] x = { 0 };
        private static int ExistIndex = 0;
        private static int NotExistIndex = 1;

        private static void Try_NotExist(int iterations)
        {
            Stopwatch st = new Stopwatch();
            st.Start();
            for (int i = 0; i < iterations; i++)
            {
                try
                {
                    int y = x[NotExistIndex];
                }
                catch (Exception)
                {
                }
            }
            st.Stop();
            Console.WriteLine("Try_NotExist({0}) = {1}", iterations, st.Elapsed);
        }

        private static void Without_Try_NotExist(int iterations)
        {
            Stopwatch st = new Stopwatch();
            st.Start();
            for (int i = 0; i < iterations; i++)
            {
                if (x.Length > NotExistIndex)
                {
                    int y = x[NotExistIndex];
                }
            }
            st.Stop();
            Console.WriteLine("Without_Try_NotExist({0}) = {1}", iterations, st.Elapsed);
        }

        private static void Without_Try_NotExist_Not(int iterations)
        {
            Stopwatch st = new Stopwatch();
            st.Start();
            for (int i = 0; i < iterations; i++)
            {
                if (!(x.Length <= NotExistIndex))
                {
                    int y = x[NotExistIndex];
                }
            }
            st.Stop();
            Console.WriteLine("Without_Try_NotExist_Not({0}) = {1}", iterations, st.Elapsed);
        }

        private static void Try_Exist(int iterations)
        {
            Stopwatch st = new Stopwatch();
            st.Start();
            for (int i = 0; i < iterations; i++)
            {
                try
                {
                    int y = x[ExistIndex];
                }
                catch (Exception)
                {
                }
            }
            st.Stop();
            Console.WriteLine("Try_Exist({0}) = {1}", iterations, st.Elapsed);
        }

        private static void Without_Try_Exist(int iterations)
        {
            Stopwatch st = new Stopwatch();
            st.Start();
            for (int i = 0; i < iterations; i++)
            {
                if (x.Length > ExistIndex)
                {
                    int y = x[ExistIndex];
                }
            }
            st.Stop();
            Console.WriteLine("Without_Try_Exist({0}) = {1}", iterations, st.Elapsed);
        }

        private static void Without_Try_Exist_Not(int iterations)
        {
            Stopwatch st = new Stopwatch();
            st.Start();
            for (int i = 0; i < iterations; i++)
            {
                if (!(x.Length <= ExistIndex))
                {
                    int y = x[ExistIndex];
                }
            }
            st.Stop();
            Console.WriteLine("Without_Try_Exist_Not({0}) = {1}", iterations, st.Elapsed);
        }

        static void Main(string[] args)
        {
            Console.WriteLine("The case where the key does not exist:");
            Console.WriteLine("1,000 iterations:");
            Try_NotExist(1000);
            Without_Try_NotExist(1000);
            Without_Try_NotExist_Not(1000);
            Console.WriteLine("100,000 iterations:");
            Try_NotExist(100000);
            Without_Try_NotExist(100000);
            Without_Try_NotExist_Not(100000);
            Console.WriteLine("1,000,000 iterations:");
            Try_NotExist(1000000);
            Without_Try_NotExist(1000000);
            Without_Try_NotExist_Not(1000000);

            Console.WriteLine("The case where the key does exist:");
            Console.WriteLine("1,000 iterations:");
            Try_Exist(1000);
            Without_Try_Exist(1000);
            Without_Try_Exist_Not(1000);
            Console.WriteLine("100,000 iterations:");
            Try_Exist(100000);
            Without_Try_Exist(100000);
            Without_Try_Exist_Not(100000);
            Console.WriteLine("1,000,000 iterations:");
            Try_Exist(1000000);
            Without_Try_Exist(1000000);
            Without_Try_Exist_Not(1000000);
        }
    }
}

Happy Error Checking!

Explicitly and Implicitly Implementing Interfaces

I read an interesting blog post from Joydip Kanjilal where he described an interesting little trick with interfaces. I, being a bit of a fan of interfaces, read the post and thought I'd throw my $0.02 in also. I couldn't pass up an opportunity to talk about interfaces. He first shows simply how to create an interface and how to implement the interface implicitly. The difference between implicitly and explicitly writing this code is what creates the different circumstances Joydip shows in his demonstration.

I'll start where he did with an interface. I'll name my interface IBloggable and I'll have a class PostContent which implements the interface.

public interface IBloggable
{
    void SendToBlog();
}

public class PostContent : IBloggable
{
    public void SendToBlog()
    {
        // Send this content to a blog
    }
}

Ok so this is the implicit implementation of the interface. Basically all I mean when I say explicitly and implicitly is whether or not you're going to define everything. If I define something explicitly I have defined everything and made it perfectly clear. I have included every detail required for precise interpretation. Notice above I have not specified to which class that method applies. So here I will now define the same thing explicitly and make sure that the SendToBlog method specifies to what it belongs.

public class PostContent
{
    void IBloggable.SendToBlog()
    {
        // Send to blog only for the interface not for implementing classes
    }
}

As Joydip pointed out so well, the first one will work in either of these circumstances, but our explicitly defined method will only work in the first example.

Example 1:

IBloggable b = new PostContent();

Example 2:

PostContent b = new PostContent();

From this we can note a couple of other interesting points here.

If we implement interface methods implicitly, we are able to use the method with objects of the interface type or of the implementing class type. If we are implementing explicitly, the method will only work on the interface. The great benefit of only allowing instances of the interface to use the method is that it encourages you to write more dynamic and maintainable code since you'll be using the interface everywhere you'll be able to switch your implementing classes quickly and easily.

This is one of many great ways to write better code. I always explicitly implement my interfaces. I've not had it bite me yet, so if anyone knows a reason to not explicitly define this code, please let me know.

One nice feature in Visual Studio which makes this nice and easy. Once you specify the interface you want your class to implement you are able to right click on it and choose Implement Interface > Implement Interface Explicitly and it will create the stubs for everything required in order to implement the interface. It will even place it all in a nice code region for you. Observe the code it generates for us in this instance.

public class PostContent : IBloggable
{
    #region IBloggable Members

    void IBloggable.SendToBlog()
    {
        throw new Exception("The method or operation is not implemented.");
    }

    #endregion
}

Happy coding.