Well, it seems that this week I have been hitting every bug and/or unexpected behavior in the .NET Framework 2 & 3. What is more frustrating is that none of these bugs will be fixed imdiately, some being scheduled for "Orcas" and some for even later releases of the Framework.
The most importants of these bugs are one on WCF reliable messaging and another one when compiling generics code. The first I will leave for another post and will concentrate on the second bug here.
I have written a piece of code similar (conceptually) to the following:
namespace CoreLibrary
{
public class BaseClass<T> where T : class, new()
{
public virtual string DoSomething()
{
T obj = new T();
return string.Format("The type used is {0}.", obj.GetType().FullName);
}
}
public class ChildClass<T, Y> : BaseClass<T>
where T : SideClass<Y>, new()
where Y : class, new()
{
public override string DoSomething()
{
T objT = new T();
Y objY = new Y();
return string.Format("The two types used for this class are {0} and {1}.", objT.GetType().FullName, objY.GetType().FullName);
}
}
public class SideClass<T>
{
public string DoSomethingElse()
{
return "Did something else!";
}
}
}
And the program to run that looks like:
namespace Program
{
class Program
{
static void Main(string[] args)
{
ChildClass<SideClass<object>, object> obj = new ChildClass<SideClass<object>, object>();
Console.WriteLine(obj.DoSomething());
Console.Read();
}
}
}
When I run the above code I get a System.BadImageFormatException.
It works out to be a bug in the compiler itself as reported here. To solve this, I had to change the BaseClass<T> to the following:
public class BaseClass<T> where T : new()
{
public virtual string DoSomething()
{
T obj = new T();
return string.Format("The type used is {0}.", obj.GetType().FullName);
}
}
By removing the class constraint from T in the base class, everything compiles and works fine. In the actual code I was using in my project, T was constrained to reference types so that I could use some better casting and stuff like that, but in reality I could do just fine without constraining so that wasn’t an issue after all.
The bug in WCF is a bit more complex and I will post more about that later on as soon as I get time to write the article.