I have the following classes:
public class HeaderBase
{
public int HeaderSize { get { return sizeof(byte); } }
public byte[] Content { get; private set; }
public HeaderBase(byte[] bytes)
{
Content = bytes;
}
}
public class BiggerHeader : HeaderBase
{
public new int HeaderSize { get { return sizeof(byte) + sizeof(UInt32); } }
public BiggerHeader(HeaderBase header) : base(header.Content)
{ }
}
I also have a templated method to marshal and instantiate the BiggerHeader
type
public static T Get<T>() where T : HeaderBase
{
HeaderBase b = new HeaderBase(new byte[]{});
T instance = (T)Activator.CreateInstance(typeof(T), b);
return instance;
}
According to MSDN:
where T : <base class name>
: The type argument must be or derive from the specified base class.
However, the value of HeaderSize
is 1 and not 5 as I would have expected. Why would this be the case, and how can I instantiate an object which will use the new
properties from derived types?
Related: Generics in C# - how can I create an instance of a variable type with an argument?