Mert Özoğul
Mert Özoğul

Reputation: 320

Calculate Value Types (int, float, string) Sizes In C# With Generic Method

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.

Upvotes: 1

Views: 475

Answers (2)

Amit
Amit

Reputation: 46323

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()).

Upvotes: 1

usr
usr

Reputation: 171178

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));
}

Upvotes: 1

Related Questions