1

I've seen a couple of similar posts but think that my scenario is more specific. Consider the following struct:

public interface ISample<T>
    where T: struct, IComparable, IFormattable, IConvertible
{
    T Value { get; }
    TimeSpan Time { get; }
}

public struct Sample<T>:
    ISample<T>
    where T: struct, IComparable, IFormattable, IConvertible
{
    private readonly T _Value;
    private readonly TimeSpan _Time;

    public Sample (T value) { this._Value = value; this._Time = TimeSpan.Zero; }
    public Sample (T value, TimeSpan time) { this._Time = time; this._Value = value; }

    public T Value { get { return (this._Value); } }
    public TimeSpan Time { get { return (this._Time); } }

    public static readonly Sample<T> Zero = new Sample<T>();

    static Sample ()
    {
        var type = typeof(T);

        if
        (
            (type != typeof(byte))
            && (type != typeof(sbyte))
            && (type != typeof(short))
            && (type != typeof(ushort))
            && (type != typeof(int))
            && (type != typeof(uint))
            && (type != typeof(long))
            && (type != typeof(ulong))
            && (type != typeof(float))
            && (type != typeof(double))
            && (type != typeof(decimal))
        )
        {
            throw (new ArgumentException("The generic argument [<T>] must be a primitive integral or floating point type."));
        }
    }
}

I need to calculate the size of this struct at runtime. Is there a reliable way to do this with generics? Since the number of types are limited, hard-coding the values is an option but not preferable. Any hints would be appreciated.

Community
  • 1
  • 1
Raheel Khan
  • 14,205
  • 13
  • 80
  • 168

1 Answers1

0

Try Marshal.SizeOf(typeof(T)) for calculating generic type size. I'm not sure if you can use if for the struct itself, but you can add the result to the struct size that you supposed to know. More info on the method here.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
Vadim K.
  • 1,081
  • 1
  • 14
  • 26