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.

Introduction to Partial Classes

I've recently written a beginner's article explaining what partial classes are and how to use them. My Partial Classes Tutorial walks you through how how partial classes work, how to create partial classes, when one would use partial classes, and a few other bits of useful information. If you don't know much about partial classes I recommend you read the article it has some useful information in it. If you have any partial class question either ask me here or comment on the article. I will be happy to answer questions.

As always, thank you very much for reading.

Creating a Simple Hello World Application Using MVC

So I am finally sitting down to play with the ASP.NET MVC Framework. I've installed Visual Studio 2008 on my machine. You can obtain a 90 day free trial of Visual Studio 2008 from Microsoft if you don't own a copy. There are also Express Editions of Visual Studio 2008.

After installing Visual Studio 2008 I installed the ASP.NET 3.5 Extensions Preview. It contains the required components to use the new MVC Framework. Now that you have it installed open up Visual Studio and create a new project. Choose the web section and select ASP.NET MVC Web Application. I named my project "HelloMvc".

 NewProjectHelloMvc

Here you can see the files currently in this empty project. Notice there are a bunch of files that it comes with including a Controller and a couple of Views.

 HelloMvcEmptySolution

So now run the application by pressing ctrl + F5. You'll see this page once you run the application.

HelloMvcStartingPage

Fairly simple for now, but hey it works. Now we should try to figure out how to create a simple static page. We'll make it look kind of like that about view that is already in there. We want it to be hello. OK, so click on the About Us link in the application. You'll be at a URL similar to this one http://localhost:64701/Home/About. So as a nice test try changing "About" to Hello in the address bar. You'll receive this nice error message which tells us the first step in creating our Hello World page.

 HelloMvcActionNotFound

Ok so we need to define an action in our controller. The Home part of our URL is saying we want to use the HomeController, so open up that file in the Controllers folder and add the following code into that file.

[ControllerAction]
public void Hello()
{
    RenderView("Hello");
}

Notice that all we needed to do here is to use the ControllerAction attribute for a method we define. We'll defined the method named Hello by added a line calling the RenderView method. Congratulations you've defined your first Controller Action. So we now refresh the page where we previously received an error message, and we're greeted with a new one. So we are on the right track.

 HelloMvcViewNotFound

Now we need to create the view that we are trying to call in our Controller Action. So we'll right click on the Home folder inside of the View folder and select Add then New Item. Here is where Microsoft has tried to trick you. They've now changed how you attach to MasterPages. Instead of picking a Web Form and checking a box you now have a new choice Web Content Form. Make sure you pick that or you'll not get a MasterPage added for you. It will look like this.

 HelloMvcAddNewView

So now that we have that empty view we can quickly add a nice message into it. So go ahead and type in some html like the following.

<h2>Hello World! MVC is here!</h2>

Now you need to go into the code of this view and place in the following.

using System;
using System.Web;
using System.Web.Mvc;

namespace HelloMvc.Views.Home
{
    public partial class Hello : ViewPage
    {
    }
}

Notice here that we need to inherit from the ViewPage class instead of the System.Web.UI.Page class. We are instead using the System.Web.Mvc.ViewPage class. This will allow our .aspx page to work as a view. Make sure to build the application and then open up the view again in the browser. Woohoo you've successfully created an MVC Controller Action and a View. And as some icing on the cake we will now add a link to our view on the MasterPage so that we can easily access this Hello View whenever we want to.

Open up the Site.Master file. It is located in the \Views\Shared. You will see an unordered list in the html. There are currently two list items in the list; Home and About Us. You will want to add a new one using the following code.

<li><%= Html.ActionLink("Say Hello", "Hello", "Home") %></li>

Now refresh the page. From anywhere on this site you can now get to the Hello World View. The method we used here took 3 arguments. The first is the text which appears for the link, the second is the name of the view, and the third is the name of the controller. The following is our final product. We have the Hello World page as well as a nice link to it.

HelloMvcHelloView

Enjoy creating simple MVC Views!

Blogging Code Snippets Using Windows Live Writer

So obviously anyone wanting to write technical blog posts will eventually require code snippets on the posts. Posting code is not very difficult. The basic part is just that you want the browser to know that your text is code and it should not apply standard html formatting to it; wrapping lines, etc. The key ingredient to this is the html tag pre. It tells the browser that the following is special. It really just means that the inner text of the tag is preformatted, and that the browser should do nothing but display the text. Very useful for displaying code snippets. Especially if the snippets are html snippets. Wouldn't it be bad if the browser rendered the code you were trying to show people.

So great we have preformatted text, but it still doesn't look nice at all. Well I could sit there and color the snippets and spend time formatting it nicely, but I use Windows Live Writer. Great tool. I blogged about why I like Windows Live Writer in the past, and the add-ins I am about to mention simply add to my admiration of this tool. There are a few great code snippet inserting tools. Which let you choose a language and it will format the code nicely including some coloring for you. Some will give you containers and fancy alternating lines. I've settled on no container without lines. It seems to work well enough for my purposes. Not too fancy, but still readable enough to allow the code to be useful to others.

I hope that is useful to people out there. I highly recommend these code snippet inserting tools. Also I recommend Windows Live Writer and the plug-ins for it. There are a lot of useful tools for this application. (Yes, I am using Windows Live Writer for this message.)

Happy blogging!

Silverlight Expired The Pain of Reinstalling

So I have been ignoring these messages I've been receiving for a while about Silverlight. Now I might not have ignored it, but it said my version of Silverlight expired. Ok so big deal. You might say, "Why not just go get a new version?" Well it says to go to a certain URL. You can't click on the URL, and you can't copy and paste the text. Typing URLs by hand is so mid 90's.

SilverlightExpiredMessage

So the really annoying part of all of this. I just now navigated to that site by typing in all of that junk. And it takes me to the Silverlight page on the Microsoft site. http://www.microsoft.com/SILVERLIGHT/default_ns.aspx

I am also annoyed that the older versions of Silverlight don't still work. So I click the download link, and when the download completes I run the install, and this pops up on my screen.

SilverlightInstallFailed

What the hell shouldn't the link that the error message sent me take me to a page where the download will just work? Since it is the URL from the error message it should send me to instructions at least. So now that my install has failed at least I have a link to click on. It takes me to this nice page where I get some Silverlight help. It has links to actually go to the pages. The kind where I don't have to type in a URL by hand.

SilverlightHelp

So it says I need to uninstall. Why wasn't I told this before I was sent to go download the Silverlight install at first? So just for kicks because I thought it was kind of funny to have it there. I clicked on the Silverlight Uninstall Instructions. The best thing ever happened. Going to that page gave me the error message again. So they actually try to have Silverlight content on the page with the instructions to uninstall Silverlight...... Now this is truly amazing. They actually have videos explaining how to uninstall Silverlight on this page, but they couldn't give me a link in the error message. They could have just said, "You will need to uninstall your current version of Silverlight. You can download a new version here." That would just be way too easy though.

SilverlightUninstall

Just thought I would share that nice bit of fun with you.

The moral of the story is probably something about not expecting error messages to give good information. Perhaps also that some install files aren't smart enough to handle an upgrade of any kind.

XNA Game Studio 2.0 Released

So I've dropped the ball on XNA. I've been meaning to read and learn about XNA for a while now. Microsoft has done something truly revolutionary here. They're taking efforts to encourage the little guy to write games for their console. As far as I know, they're the first console to do this. Please correct me if I am wrong about that. I'll get to the point now. Microsoft released a new version of XNA Game Studio which is the development environment for working with XNA games. I'm a version behind...

XNA Game Studio Express works along side Visual Studio 2005. In previous version I don't think you were able to use anything except for the C# Express Edition. According to the XNA web site, the new version supports the following versions of Visual Studio.

  • Visual C# 2005 Express Edition
  • Visual Studio 2005 Standard Edition
  • Visual Studio 2005 Professional Edition
  • Visual Studio 2005 Tools for the Microsoft Office System
  • Visual Studio 2005 Team Edition for Software Architects
  • Visual Studio 2005 Team Edition for Software Developers
  • Visual Studio 2005 Team Edition for Software Testers
  • Visual Studio 2005 Team Edition for Database Professionals
  • Visual Studio 2005 Team Suite

They also have some nifty cool starter kits for those of you who hate beginning projects from scratch. They should also be very helpful while learning to develop games using XNA. There are also tutorials and articles on the site which should help us along while learning XNA.

For those of you who somehow missed XNA completely, it is a game development framework. It helps you develop games for Windows as well as Xbox 360.

Now that I've got an Xbox 360 I think I'll finally hop on board if I get the chance. I am only one major version behind on this one.