Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Convert T to long

I have a generic class (C#),

class MyClass<T> where T : struct, IComparable<T>
{
    public T filelocation;
}

T can be either UInt32 or UInt64 (nothing else).

I need to convert filelocation to a long to seek in a file...

I have tried the following

long loc = (T)myclass.filelocation;

long loc = (T)(object)myclass.filelocation;

But nothing seems to work...

Any ideas?

like image 691
Mike Christiansen Avatar asked May 02 '11 13:05

Mike Christiansen


2 Answers

Call Convert.ToInt64.

Writing (object)fileLocation creates a boxed UInt32.
Boxed value types can only be unboxed to their original value types, so you cannot cast it in one step to long.
You could write (long)(ulong)fileLocation, but that will fail for a uint for the same reason.

like image 159
SLaks Avatar answered Sep 17 '22 16:09

SLaks


Try Convert.ToInt64.

long loc = Convert.ToInt64(myclass.filelocation);
like image 23
BrandonZeider Avatar answered Sep 20 '22 16:09

BrandonZeider