Z
Zachary Turner
Consider the following generic class
class MyClass<T>
{
private MyInterface _SomeInterface;
private string _SomeFormatString;
public string GetSomeFormattedString()
{
T[] ArrayOfTs = _SomeInterface.GetArrayOfTs();
return String.Format(_SomeFormatString, ArrayOfTs);
}
}
Assume _SomeFormatString is a valid format string containing a number
of parameter replacement strings equal to the number of items in
ArrayOfTs.
Utilizing this class as follows:
MyClass<object> ObjectClass = new MyClass<object>();
string FormattedString = ObjectClass.GetSomeFormattedString();
throws an exception on the call to String.Format(). It happens because
the compiler invokes the wrong overload. It appears to invoke the
overload
String.Format(string Format, object arg)
instead of the correct one
String.Format(string Format, params[] object args)
Is this a feature, or a bug? I'm noticing more and more that the .NET
Generics engine seems to actually do very little at compile time, which
in my mind is almost defeating the purpose of Generics in the first
place.
I can work around the problem by calling
return String.Format(_SomeFormatString, (object[])ArrayOfTs);
or perhaps more robustly (in case T is something other than object) by
the rather obtuse code
object[] ConvertedValues = Array.ConvertAll<T, object>
(
Values,
delegate(T Thing) { return (object)Thing; }
);
return String.Format(_SomeFormatString, ConvertedValues);
class MyClass<T>
{
private MyInterface _SomeInterface;
private string _SomeFormatString;
public string GetSomeFormattedString()
{
T[] ArrayOfTs = _SomeInterface.GetArrayOfTs();
return String.Format(_SomeFormatString, ArrayOfTs);
}
}
Assume _SomeFormatString is a valid format string containing a number
of parameter replacement strings equal to the number of items in
ArrayOfTs.
Utilizing this class as follows:
MyClass<object> ObjectClass = new MyClass<object>();
string FormattedString = ObjectClass.GetSomeFormattedString();
throws an exception on the call to String.Format(). It happens because
the compiler invokes the wrong overload. It appears to invoke the
overload
String.Format(string Format, object arg)
instead of the correct one
String.Format(string Format, params[] object args)
Is this a feature, or a bug? I'm noticing more and more that the .NET
Generics engine seems to actually do very little at compile time, which
in my mind is almost defeating the purpose of Generics in the first
place.
I can work around the problem by calling
return String.Format(_SomeFormatString, (object[])ArrayOfTs);
or perhaps more robustly (in case T is something other than object) by
the rather obtuse code
object[] ConvertedValues = Array.ConvertAll<T, object>
(
Values,
delegate(T Thing) { return (object)Thing; }
);
return String.Format(_SomeFormatString, ConvertedValues);