There is no generic way of doing it because we don't have static interfaces so there is no way for the compiler to know that each of the numeric types have a "Parse" method. I tried to do it with dynamic but unfortunately ((dynamic)T) is not valid syntax. You can do it with reflection pretty easily and even take advantage of the fact that each closed generic is effectively a separate type and do the work once (per closed generic) in a static constructor like this:
public class DemoClass<T> where T : struct
{
private static readonly Func<string, T> _parser;
static DemoClass()
{
var method = typeof(T).GetMethod("Parse", new[] { typeof(string) });
if(method == null)
_parser = s => { throw new Exception(String.Format("Type has no Parse method
{0}", typeof(T))); };
else
_parser = s => (T)method.Invoke(null, new[] { s });
}
public T value;
public void FromText(string rawValue)
{
value = _parser(rawValue);
}
}
Note that I set this up to throw an exception when you call FromText not
when you create the class. I'm pretty sure that throwing an exception from
static constructor is a BAD idea(TM).
Michael M. Minutillo
Indiscriminate Information Sponge
http://codermike.com
On Sat, Jun 4, 2011 at 12:58 PM, Greg Keogh <[email protected]> wrote:
> Surely there's very few types that a) you're using, that b) offer that
> Parse method. Could you save the reflection call and simply do something
> like
> if (typeof(T) is decimal) { decimal.Parse(...); }
> elseif (typeof(T) is int) { int.Parse(...); }
>
> I can’t cast a double, int or long to the generic type T which is
> constrained to be a struct. Hmmm .. why?
>
> As David says, if I’m doing if typeof(X) in the class then there’s no
> point in it being generic.
>
> The class I’m using is in fact a wrapper around a two-dimensional array of
> the T (a matrix of T). It just seemed natural to have a generic class to
> hold the matrix of T values, and it was working lovely until I stumbled upon
> this brain-teaser of parsing a string to set one of the T values.
>
> Greg
>
<<image001.png>>
