Brendan Enrick

Daily Software Development

Old Blog Favorites

I am somewhat partial to a few of the posts from my previous blog. For some of these posts, I just like the post, some the content about which the post was written, and some were just popular posts.

Installing SQL Server Management Studio with SQL Server: My most popular post is one written about a painful experience installing SQL Server's client tools. Sadly the popular post is out of date. My first post about the topic I found a solution that worked and managed to install the software. I late found out that there was a better way and I updated the post. The problem is that Google continued to send traffic to the old one. For my blog it was a pretty popular post. it has had over 25,000 views.

The original version - Installing SQL Server Management Studio with SQL Server

The current version - SQL Server Client Tools Installation

Visible Whitespace in Visual Studio: Another post written about a traumatic experience was when I accidentally used a keyboard shortcut and enabled visible white space. It caused a blue dot to show for every space character in visual studio. Wow was it hard to read my code with that on. Well I Googled for it, and at the time I didn't receive any results. There are some now my post is one of them. I also didn't notice the option to turn it off. I used an algorithm I like to call brute force to figure out the keyboard shortcut I typed. It was Ctrl + E + S. Comments let me know of a bunch of other ways to solve the problem for different configurations and versions of Visual Studio.

Visible Whitespace in Visual Studio

Return Within a C# Using Statement: IDisposable objects are nice to work with. I prefer not dealing with external resources, which is generally what you're doing with disposable objects, but having this interface makes it a little bit nicer. I wrote a post telling people it was safe to return from within the using statement, because the using statement will make sure that the object is disposed. In the lifetime of the post only one person actually challenged me on it and asked me to provide code showing that what I said is true. I of course responded to that comment and then posted a response on this blog. My response includes sample code showing that using statements make sure that the object is disposed.

If you like the second post make sure you thank Lambros Kaliakatsos for commenting on the first one.

The original post - Return Within a C# using Statement

The follow up including sample code - Returning From Inside a Using Statement

Performance with DropDownLists and ViewState: One thing that it seems a lot of ASP.NET developers still don't understand very well is ViewState. Page lifecycle stuff seems to really be fueling the MVC craze these days. I wrote a post talking about how ViewState can hurt the performance of your applications if you let it get out of hand. The example I used is the drop down list, but it can certainly get a bit crazy from grids, repeaters, etc. I wrote an article basically saying that you should try to avoid ViewState if you're going to have too much of it. I later followed up with a post about how to use a DropDownList without ViewState. Some people are concerned that you will not be able to use the SelectedValue property, but you can if you wire it up correctly. It is all about understanding that painful Page Lifecycle.

Performance with DropDownLists and ViewState

Using a DropDownList without ViewState

There are plenty of other posts I like in there, but I think I've bored my readers enough for one day. I've got a couple of posts lined up which should be a little bit more interesting than this one, so keep reading. As always, have a great day.

Returning From Inside a Using Statement

A while back I wrote a blog post regarding this topic. In that post I explain that it is safe to use a return statement inside a using block, because the using block will handle the disposing of the defined IDisposable object. This is one truly great ability of the IDisposable interface. It makes it very important to use in my opinion. The using block in combination is very nice, because it handles the disposal for you.

One of my commenter on that post asked me if I was certain that the return statement was safe. He asked this because he couldn't find it in the documents. He also asked me if I had any code showing that this behavior works as I claim it does. I quickly wrote this simple little piece of code which works to demonstrate this behavior.

In my example I have a few things. I have a class which implements IDisposable and all it does to dispose is to write to the console. I then wrote 3 methods which each create and instance of this class in a using statement. One class is normal; it returns after the using statement is complete. The other two end abruptly. One of them returns from within the using statement, and the other throws an exception within the using statement.

 

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Application Starting\n");

        Console.WriteLine("Before normal method");
        NormalMethod();
        Console.WriteLine("After normal method\n");
        
        Console.WriteLine("Before return method");
        ReturnFromMethod();
        Console.WriteLine("After return method\n");

        Console.WriteLine("Before Throw method");
        try
        {
            ThrowFromMethod();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Caught the Exception: " + ex.Message);
        }
        Console.WriteLine("After Throw method\n");

        Console.WriteLine("Application Ending");
    }

    private static void NormalMethod()
    {
        using (MyDisposable myDisposable = new MyDisposable())
        {
            // do nothing
        }
        return;
    }

    private static void ThrowFromMethod()
    {
        using (MyDisposable myDisposable = new MyDisposable())
        {
            throw new Exception("This is the exception");
        }
    }

    private static void ReturnFromMethod()
    {
        using (MyDisposable myDisposable = new MyDisposable())
        {
            return;
        }
        Console.WriteLine("DO NOT WRITE THIS!!!");
        return;
    }

    class MyDisposable : IDisposable
    {
        #region IDisposable Members

        public void Dispose()
        {
            Console.WriteLine("I am disposing!");
        }

        #endregion
    }

}

This code returns the following result. In this screen shot you should notice that each time it calls the dispose method of the MyDisposable object.

 UsingStatementReturn

Give the code a shot in a console application, and you will see that the using statement cleans up disposable objects pretty nicely.

Download this sample code as a small C# console application here.

I hope you enjoyed this post. I would also like to thank Lambros for the good comment. I hope to get more feedback from you in the future.

Optional and Named Parameters in C#.... Finally

I've used Python a decent amount in the past. I enjoy the language and I've taught the language to non-computer science students at Kent State University. There are plenty of things that I really love about that language. I could write plenty of blog posts regarding how totally awesome python is. I tend to use it for quick little bits of code. I don't use too much Python for production code, but I do like a lot of the language features.

One of the big pieces of Python I enjoy is the ability to define a default value for a parameter in a method. This allows for optional parameters. Wonderful stuff. I hate having to make extra overloads to handle default parameters which pass in either the right ones or values specifying that the value is missing. Way too much handling just to handle this case.

Named parameters are also a lot of fun since you're able to specify which parameter you're passing. It works pretty well in Python. I don't know how useful it will be in C#, but it is a neat feature which doesn't add much complexity to the language.

In the session I am sitting in at the PDC I am listening to a speaker talking about how this is coming down the pipe for C#. I would guess C# 4.0 will include these features. Now I can finally get rid of all of the extra overloads. I can finally just have my default parameters. No more of the extra overloads or passing in missing values.

For a lot of code we want to allow for customization, but at the same time we want to be able to have default values since the 90% case doesn't require the customization. We need the ability to customize some, so these features in combination could allow a method with say 8 parameters have you specify 2 of them and then name the 3rd one you want to specify. This should help clean up code and allow us to be concerned only with the code which is currently important to us. No need to worry about all the extra parameters in the method that we don't care about.

Finally!!! I've been wanting default and named parameters for a looooong time.

Dynamically Typed Objects in C#

In the past the C# language obtained a new feature allowing it to declare variables as type "var". It didn't really do any dynamic typing though. For the most part the var is just there for developer convenience. Some people have complained about this in the past. Stating that C# 3.0 doesn't have dynamic types. The problem is that with that it is figuring out when compiling what type the variable is.

I am currently sitting in the Los Angeles Convention Center for the PDC 2008. I am watching a session on the future of C#. One of the interesting demos we're seeing in this is some of the new dynamic typing that is coming down the pipe. Variables are being defined with the type "dynamic" this is very cool because it is being figured out at runtime and not at compile time. It seems to be a very powerful ability of the language even in this early stage. Perhaps we'll see some new stuff from this some time soon.

Looks like they're combining the dynamic and var so they work very well together.

Throwing Away Return Values

So it probably took me 15 seconds to track down this error in my code, and those wasted seconds, while very minor, are exactly why I wish Visual Studio or ReSharper or some program would alert me to what I've mistakenly done. It is easy with some methods to throw away a return value without noticing.

If I am calling a method which has a return value I am ignoring, it might be nice if it made it a little more obvious I am doing so. Perhaps an underline with a note explaining that I am not processing a return value. Sure lots of people ignore return values all the time, but they really shouldn't be. The return value probably exists for a reason.

As an example assume you want to get a substring.

string myString = "LongStringWithTooMuchStuffSoItProbablyNeedsToBeCutDownToSize";
myString.Substring(5,10);
Console.WriteLine(myString);

Looking at that code it is pretty easy to miss the fact that I am not doing anything with the return value. Right now the value written to the console is "LongStringWithTooMuchStuffSoItProbablyNeedsToBeCutDownToSize". I am just ignoring the value that substring is returning. This means I am not actually doing anything. I am just printing out the original string. What I really should have written is this.

string myString = "LongStringWithTooMuchStuffSoItProbablyNeedsToBeCutDownToSize";
myString = myString.Substring(5,10);
Console.WriteLine(myString);

It wouldn't be that difficult for a program to detect unused return values. I am already informed when I don't use variables. Since plenty of plug-ins for visual studio already read method signatures, one of them could easily detect that I am ignoring the return value of that method. Ah the little things. Not too big a deal, but kind of annoying since I executed my program once and had to look to see why my code didn't work as expected.

Maybe some program does mention this already, or maybe there is some setting I need to enable to do this. Please let me know if you know of one.

Nested Using Statements

I think it is a great idea to always be reading code. You may learn more than you intend to sometimes. Read an article to learn one trick and you may learn a completely different one. Earlier today I was reading some code written by Steve Smith. He wrote an extension method for the System.Web.UI.Control class called RenderControl. I was just looking to see what he had written, and from this little snippet of code I learned a cool trick.

 

public static string RenderControl(this System.Web.UI.Control control)
{
    StringBuilder sb = new StringBuilder();
    using (StringWriter sw = new StringWriter(sb))
    using (HtmlTextWriter textWriter = new HtmlTextWriter(sw))
    {
        control.RenderControl(textWriter);
    }
    return sb.ToString();
}

In the past I would have nested my using statements like this.

public static string RenderControl(this System.Web.UI.Control control)
{
    StringBuilder sb = new StringBuilder();
    using (StringWriter sw = new StringWriter(sb))
    {
        using (HtmlTextWriter textWriter = new HtmlTextWriter(sw))
        {
            control.RenderControl(textWriter);
        }
    }
    return sb.ToString();
}
So now I can go ahead and save myself some curly braces and extra indentation.

I enjoy all the little things one can learn from reader the code others write.

Difference Between Value Types and Reference Types in C#

I recently wrote an article for C# beginners in which I explain the differences between value types and reference types in C#. It was published on ASP Alliance today. If you're new to C# or are even a little fuzzy on these concepts, I recommend you check it out. Please offer some feedback good or bad. I really do read and appreciate feedback I receive. I try to improve what I write based on what others tell me.

I've seen so many people run aground with errors stemming from misunderstandings about and just forgetting the importance of value and reference types.

Good day and happy programming!

Visual C# 2008 Keyboard Shortcut Reference

As I've said previously, I am working with developers who are just beginning to learn the tools of the trade. They have a long way to go working with plenty of applications. All people always have more they can learn, so I'll pass along a useful reference here. I found this great reference sheet from Microsoft that has a bunch of key-bindings for Visual C# 2008. It is a PDF poster you can use to reference different shortcuts available to you.

http://www.microsoft.com/downloads/details.aspx?familyid=e5f902a8-5bb5-4cc6-907e-472809749973&displaylang=en

Return Within a C# Using Statement

While writing some code earlier today I needed to return from within a using statement. Doing these sorts of things always makes me appreciate the using statement and how wonderful it really is, so I decided to write about it here. As many of you know the using statement in C# is a good tool for managing types which will be accessing unmanaged resources. Some examples of these are SqlConnections, FileReaders, and plenty of other similar types. The key to these is that they all implement the IDisposable interface. This means that they all need to be cleaned up carefully after using them.

The using statement is great because it guarantees that the declared object is disposed no matter how the execution completes. Whether you reach the end curly brace marking the end of the using statement, throw and exception, or return from a function, the using statement will call the dispose method and clean up the object.

This was important in my code because I was able to return directly from within the using statement without worrying about whether or not eh dispose method will fire. Whenever I use an object which accesses unmanaged resources I always always always put it in a using statement.

It is very important to use a using statement, because it will give you this guarantee that the object will be disposed of correctly. The object's scope will be for the extent of the using statement, and during the scope of the object it will be read-only if defined in the using statement. This is also very nice, because it will prevent this important object which manages the unmanaged from being modified or reassigned.

This is safe to do, because of how great the using statement is. No matter which return we hit we know the XmlReader will be disposed of correctly.

using (XmlReader reader = XmlReader.Create(xmlPath))
{
    // ... Do some work...
    if (someCase)
        return 0;
    // ... Do some work...
    if (someOtherCase)
        return 1;
}
return -1;

Happy coding. Enjoy this powerful tool.

Update: I've posted a follow up to this post with a code sample. It shows that you can return from inside of a using statement in C#.

Differences Between Structures and Classes in C#

Earlier today I was looking for a good reference outlining the differences between structs and classes in C#. I wanted a refresher on the subject, because I've been doing a reasonable amount of teaching lately. At Lake Quincy Media we have hired a couple of developers currently in school. In bringing them up to speed, I've been explaining a lot about programming languages, paradigms, etc. and it is nice to have good references to make sure that I am not passing along misinformation. In my quest to make sure that I'm remembering things correctly I found a great resource showing the differences between C# structs and classes. It is a very nice reference. I has links to different sections and code examples showing the differences it lists. I'll definitely be recommending that these guys take a look at this resource.

Note: In my opinion the best one thing to remember when thinking about structs and classes is that structs behave like value types and classes like reference types. If you know how to interact with each of those then you'll understand a lot of the differences right away.

Happy Programming Everyone!