Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Casting from generic to value type

Tags:

c#

generics

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.

like image 221
Thomas Avatar asked Feb 15 '26 12:02

Thomas


1 Answers

This will compile and will cast the result to T:

Value = (T)(object)A;
like image 53
Yacoub Massad Avatar answered Feb 18 '26 01:02

Yacoub Massad