Thomas
Thomas

Reputation: 12107

C#: Casting from generic to value type

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.

Upvotes: 3

Views: 974

Answers (2)

dpmemcry
dpmemcry

Reputation: 117

try this,

var res = (T)Convert.ChangeType(val, typeof(T))

Upvotes: 0

Yacoub Massad
Yacoub Massad

Reputation: 27861

This will compile and will cast the result to T:

Value = (T)(object)A;

Upvotes: 4

Related Questions