Get Type Size - CSharp System

CSharp examples for System:Type

Description

Get Type Size

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Linq.Expressions;
using System.Linq;
using System.Collections.Generic;
using System;// w w  w .j  a v  a 2  s.  c  o m
using SafeILGenerator.Ast.Nodes;

public class Main{
    static public int GetTypeSize(Type Type)
      {
         Type = GetSignedType(Type);
         if (Type == typeof(sbyte)) return sizeof(sbyte);
         if (Type == typeof(short)) return sizeof(short);
         if (Type == typeof(int)) return sizeof(int);
         if (Type == typeof(long)) return sizeof(long);
         if (Type == typeof(float)) return sizeof(float);
         if (Type == typeof(double)) return sizeof(double);
         if (Type == typeof(IntPtr) || Type.IsPointer || Type.IsByRef) return sizeof(void*);
         if (Type.IsAnsiClass) return sizeof(IntPtr);
         Console.Error.WriteLine("Warning. Trying to get size for {0}", Type);
         return Marshal.SizeOf(typeof(IntPtr));
      }
}

Related Tutorials