Tuesday, October 11, 2011

What is a size of DateTime type in C#?

What is a size of DateTime type in C#? - A trivial question, unexcitingly facing few obstacles. Self-explanatory code below describes how you can't get it and how you can (and yes, it's 8 bytes):
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
}
}
}

2 comments:

Anonymous said...

thanks! very helpful

G said...

The ode is broken and cannot be trusted. It returns 4 for bool and 1 for char. Neither of those are correct, if you inspect in-memory representations in a debugger. A better way to measure it would be to create an array of it and measure the distance between pointers to elements.