Archive for the ‘.Net’ category
Sharp Code Challenge
November 29th, 2007
The people over a C# Corner are running a programming contest for WPF applications. Contests like these are great. I don't think a site like C# Corner could buy better advertising and garner as much good will in any other way. I wonder why other companies don't do something similar. Google has been doing this for a couple of years.
Microsoft has really hit a home run with WPF and with .Net. But they have really fell flat on their face with Vista. What they should do it have a contest like this. "Write a program in WPF that adds to the Vista experience and win $100,000." I imagine coders all over the world writing cool new system utilities and other programs for the money and fame. This would be a huge home run for Microsoft, and cost them so little. I bet they spend more than $100,000 on toilet paper every year. Microsoft would show that they are serious about public input, would get their developer community excited, get a lot of much needed good will, and improve Vista.
Using and IDisposable
November 7th, 2007
In .Net land, classes that hold onto resources resources that need to be cleaned up after usage should impliment IDisposable. These resources can include database connections, input or output streams, and unmanaged resources such as window handles.
There are a number of classes in the System.* namespaces that implement IDisposable. When you use a class that impliments this interface, it is your responsiblity to call .Dispose() when done with the class. When you author a class that holds onto valuable resources such as those listed above, you should impliment IDisposable and call Dispose on any composite objects your class is referencing that impliment IDisposable, plus do any other cleanup that is needed to prevent memory leaks such as releasing event handlers. Remember, if one of your objects handles an event from another object, that other object has a reference to your object and therefore garbage collection will not occur on your object (memory leak).
Microsoft tried to make it easy to use IDisposable objects in C# by adding the using block to the language:
using(SomeDisposableClass x = new SomeDisposableClass())
{
//some work here
}
The code snippet above will always call x.Dispose() when the code execution leaves the block. Pretty handy, right. Well, not really. What is not obvious about this code block is that it silently eats exceptions. The following code block does the exact same thing as the using block:
SomeDisposableClass x = new SomeDisposableClass();
try
{
//some work here
}
finally
{
x.Dispose();
}
Any exception is just lost. It is never handled. This is very, very bad. When writing code that uses IDisposable, *never* use using. At very least do something like this:
SomeDisposableClass x = new DisposableClass();
try
{
//some work here
}
catch(Exception ex)
{
throw ex;
}
finally
{
x.Dispose();
}
Now why would Microsoft give us such a dangerous language feature in C#? I have read that it was to encourage developers to dispose of resources. I don't buy it. In my mind, there are three alternatives to the current using block that would have been better. The first is simple, just have using throw any exception it encounters!
My second idea is to create a using block with a catch:
using(SomeDisposableClass x = new SomeDisposableClass())
{
//some work here
}
catch(Exception ex)
{
throw ex;
}
In my imagination, the statement above always creates a finally in the IL that disposes of x.
My third idea is to modify try/catch/finally to handle IDisposable types:
try(SomeDisposableClass x = new SomeDisposableClass())
{
//some work here
}
catch(Exception ex)
{
throw ex;
}
The only wrinkle in this third idea is that a programmer may choose to write a finally block a do some custom logic to dispose of the x object. I am sure the compiler could detect this condition and handle it acordingly. All in all, I like me second idea the best.
I think it is much more dangerous to silently eat exceptions than it is to create memory leaks. Memory leaks just cause computers to get slow or crash. Silent exceptions are not only difficult to debug, but could be causing data corruption that is not detected during the development and testing phases of the software life-cycle. Put it this way: Memory leaks are George Bush evil, data corruption is Hitler + Stalin evil. I would happily welcome Microsoft modifying or deleting the using statement from the C# language.
Something New Every Day
October 26th, 2007
Today I ran into an issue that I had not encountered in C#, which is getting unusual for me as I have been writing .Net apps in C# since 2001. When initializing a private instance variable, .Net does not allow a reference to "this". Some nugget of knowledge on this subject is floating around in the back of my head, but did not float to the front until I got an error in the VS IDE today. Here is an example:
public class Blah : BlahBase
{
private MyType t = new MyType(this); //Doesn't work!
}
In this example, I wanted the instance of MyType to hold a reference to its parent object. I won't go into all of the reasons here, but this pattern makes it possible to simplify a lot of things in my Blah class. Additionally, I need to be able to instantiate a lot of objects of type MyType, and also do it in any class types that inherit from BlahBase. My descendant classes will have a number of constructors, so doing initialization in all of these constructors of the MyType instance fields will become cumbersome and I could very easily introduce bugs with one missing line here or there.
To give a reference to Blah (or any given descendant class of BlahBase) to an instance of MyType at declaration, I decided to turn to reflection. In the BlahBase constructor, I looped through all the the Non-pubic, Instance fields of the current type using this.GetType(). I then check the type of each field to see if it is a MyType, and call FieldInfo.GetValue() to get a reference to the object, and Invoke() to set the reference to "this" via reflection as well. While the reference is not actually given to the MyType instance at initialization, it is given to each MyType instance before anything in in a child class of BlahBase can use it.
I keep telling myself that this is bad. Calling things via reflection is not very type-safe. Errors tend to happen at runtime instead of compile time. Additionally, reflection is slower than direct method calls or assignments. But really, I am probably dealing with 20 instances of MyType as a worst case. The performance difference is not going to be very bad. I will tend to write cleaner, more bug free code using this structure, as will other developers using BlahBase as a base type.
However, this is not type safe. The wrong change to MyType could cause a run-time error in the future. However, this is an error that will be very easily detected in testing. I am willing to trade for the over-all better OOP design here, and more developer productivity.
