Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic conversion with Int64

Tags:

c#

generics

I have a generic method in a MySQL connector witch make generic conversion. I simplify it for the question, cause it makes lot of things. At the end, it make a generic conversion and work fine, but I have a problem to convert Int64 to Int32.

object var1 = (long)64;
int? var2 = Select<int?>(var1); // ERROR Int32Converter from Int64

public T Select<T>(object value)
{
  return (T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value);
}

How can I fix it ?

like image 779
A.Baudouin Avatar asked Dec 08 '25 06:12

A.Baudouin


1 Answers

Can't you use Convert.ChangeType instead?

int value = Convert.ChangeType(var1, TypeCode.Int32);

or

int value = Convert.ToInt32(var1);

note that these will throw exceptions if var is outside the allowable range of Int32

like image 139
thecoop Avatar answered Dec 09 '25 18:12

thecoop