1

Say i have two generic methods:

int GetValue<T>() where T: unmanaged
{}

int GetAnotherValue<T>()
{}

I need to forward a call to one of those methods like this:

void Init<T>()
{
    int i;
    //here is my problem
    if( T is unmanaged)
        i = GetValue<T>();
    else
        i = GetAnotherValue<T>();
}

I do not figure how to dispatch the call based on the generic type T. Can someone help me? Thanks.

dzAdel
  • 11
  • 1
  • 1
    What's the context here? Why are you doing this? – Dai May 24 '22 at 20:30
  • Does this answer your question? [How do I check if a type fits the unmanaged constraint in C#?](https://stackoverflow.com/questions/53968920/how-do-i-check-if-a-type-fits-the-unmanaged-constraint-in-c) – canton7 May 24 '22 at 20:45
  • static unsafe int SizeOf() where T: unmanaged => sizeof(T); static int GetSize() => is unmanaged ? SizeOf : IntPtr.Size; //here is my pb. – dzAdel May 24 '22 at 20:54
  • Not sure where you are going with that code, but it's probably incorrect. If you are trying to find the size for interop: A type which is not `unmanaged` is not `IntPtr.Size` big, it depends on what the marshaller is doing. You could just use `Marshal.SizeOf` anyway. And if you want the *managed* size, you can just use `sizeof` either way. – Charlieface May 24 '22 at 21:24
  • I need to allocate an array based on a generic type T. if T is managed then the size of each item is the size of a reference (IntPtr.Size) otherwise T is a struct and i have to call SizeOf. Marshal.SizeOf do not accept generic parameter. – dzAdel May 24 '22 at 21:41
  • @dzAdel I can't think of a legitimate reason why you would be doing that... – Dai May 25 '22 at 03:56
  • "if T is managed then the size of each item is the size of a reference (IntPtr.Size)" not sure where you get that from: if it's not `unmanaged` it might still be a `struct` and not that size. Furthermore, newer versions of `Marshal.SizeOf` *do* take a generic parameter, and even on older versions, you can just do `Marshal.SizeOf(typeof(T))`. And I also see no reason why you would do this: if you are trying to marshal it manually, you need to know the exact type anyway – Charlieface May 25 '22 at 08:53

0 Answers0