3

I have a method that parses a string and converts the result to a generic type.
For example (pseudo code):

let S be a string.. and Value my generic type
if (generictype == int) Value = int.parse(S);
else if (generictype == float) Value = float.parse(S);

The problem is that I can't even get the cast to work:

T Value;
if (typeof(T) == typeof(float))
{
    var A = 1.0f;
    Value = A       // doesn't compile
    Value = A as T; // doesn't compile
    Value = (T)A;   // doesn't compile
}

What do I not understand is that we know for a fact that T is a float in this code, but I can't write a float to it.

The goal is to parse numbers of different types from strings. In each case, I KNOW for sure the type, so there is no question of handling someone passing the wrong type, etc.

I am trying to see if I can have a single method, with generic instead of several ones.

I can do:

Value = ParseInt(S);
Value = ParseFloat(S);
etc...

But I am trying to do:

Value = Parse<int>(S);
Value = Parse<float>(S);
etc...

Once again, there is no question of mismatch between the type of 'Value' and the type passed as a generic.

I could make a generic class and override the method that does the parsing, but I thought there could be a way to do it in a single method.

Thomas
  • 10,933
  • 14
  • 65
  • 136
  • it can't be done, the closest you can get would be if you applied a strategy to do the parsing but although you could get the sintax you want, it would be the same amount of work in the end. The `.Parse` method is static and not part of any interface so no way of getting around it – Sebastian Piu Jan 16 '16 at 20:56
  • 1
    You should probably not write a generic method or class if it isn't prepared to handle all types thrown at it. Since there is no way for you to declare a constraint that says "must be int or float or ..." or "must have a static Parse method", then you should probably not create the method or class generic. – Lasse V. Karlsen Jan 16 '16 at 20:58
  • 1
    @Thomas, Try the following `public static T To(string value) => (T)Convert.ChangeType(value, typeof(T));` – tchelidze Jan 16 '16 at 21:02
  • Check this http://stackoverflow.com/q/983030/1882537 – ASalameh Jan 16 '16 at 22:27

2 Answers2

3

This will compile and will cast the result to T:

Value = (T)(object)A;
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
0

try this,

var res = (T)Convert.ChangeType(val, typeof(T))
dpmemcry
  • 117
  • 1
  • 4