using System;
namespace DateTimeSizeExample
{
public struct TypeSizeProxy<T>
{
public T PublicField;
}
public static class SizeCalculator
{
public static int SizeOf<T>()
{
try
{
return System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
}
catch (ArgumentException)
{
return System.Runtime.InteropServices.Marshal.SizeOf(new TypeSizeProxy<T>());
}
}
public static int GetSize(this object obj)
{
return System.Runtime.InteropServices.Marshal.SizeOf(obj);
}
}
internal class Program
{
private static void Main(string[] args)
{
// Error: 'System.DateTime' does not have a predefined size, therefore sizeof can only be used in an unsafe context
// (consider using System.Runtime.InteropServices.Marshal.SizeOf)
//int s1 = sizeof(DateTime);
// Run time Argument Exception: Type 'System.DateTime' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed
//int s2 = System.Runtime.InteropServices.Marshal.SizeOf(typeof(DateTime));
int dateTimeSize = SizeCalculator.SizeOf<DateTime>(); // 8 bytes
}
}
}
namespace DateTimeSizeExample
{
public struct TypeSizeProxy<T>
{
public T PublicField;
}
public static class SizeCalculator
{
public static int SizeOf<T>()
{
try
{
return System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
}
catch (ArgumentException)
{
return System.Runtime.InteropServices.Marshal.SizeOf(new TypeSizeProxy<T>());
}
}
public static int GetSize(this object obj)
{
return System.Runtime.InteropServices.Marshal.SizeOf(obj);
}
}
internal class Program
{
private static void Main(string[] args)
{
// Error: 'System.DateTime' does not have a predefined size, therefore sizeof can only be used in an unsafe context
// (consider using System.Runtime.InteropServices.Marshal.SizeOf)
//int s1 = sizeof(DateTime);
// Run time Argument Exception: Type 'System.DateTime' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed
//int s2 = System.Runtime.InteropServices.Marshal.SizeOf(typeof(DateTime));
int dateTimeSize = SizeCalculator.SizeOf<DateTime>(); // 8 bytes
}
}
}