1

I want to write method which calculate value types size. But i can't give value types (int, double, float) as method parameter.

   /*
    *When i call this method with SizeOf<int>() and 
    *then it returns 4 bytes as result.
    */
   public static int SizeOf<T>() where T : struct
   {
       return Marshal.SizeOf(default(T));
   }

   /*
    *When i call this method with TypeOf<int>() and 
    *then it returns System.Int32 as result.
    */
   public static System.Type TypeOf<T>() 
   {
       return typeof(T);
   }

I don't want it that way.I want to write this method as below.

   /*
    *When i call this method with GetSize(int) and 
    *then it returns error like "Invalid expression term 'int'".
    */
   public static int GetSize(System.Type type)
   {
       return Marshal.SizeOf(type);
   }

So how can i pass value types (int, double, float, char ..) to method parameters to calculate it's size as generic.

1

2 Answers 2

1

The reason you get an error for GetSize(int) is that int is not a value. You need to use typeof like so: GetSize(typeof(int)), or if you have an instance then: GetSize(myInt.GetType()).

Sign up to request clarification or add additional context in comments.

Comments

1

Your existing code just works:

public static int GetSize(System.Type type)
{
    return Marshal.SizeOf(type);
}

Not sure where that error is coming from that you posted but not from this. If you want to you can make this generic:

public static int GetSize<T>()
{
    return Marshal.SizeOf(typeof(T));
}

2 Comments

It appears the mystery about OPs error message is due to calling GetSize(int) instead of GetSize(typeof(int))
Has he posted the code it would have been obvious. Good guess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.