I have this generic list and I want to get the byte size of the type like if T is string or int etc., I tried both ways as written in getByteSize(), and just to let you know I am using only one way at a time ...
but when I try to compile, it gives an error saying "Error: The type or namespace name 'typeParameterType' could not be found (are you missing a using directive or an assembly reference?)"
public class iList<T> : List<T>
{
public int getByteSize ()
{
// way 1
Type typeParameterType = typeof(T);
return sizeof(typeParameterType);
// way 2
Type typeParameterType = this.GetType().GetGenericArguments()[0];
return sizeof(typeParameterType);
}
}
And idea what I am doing wrong here?
If you want to print the size and value of the Byte use the following code 3. To print the size, the maximum and minimum value of all primitive data type use the following code "S.No. Data Type Size Min. Value Max.
The size of a data type is given by (name of datatype).SIZE. The maximum value that it can store is given by (Name of data type).MAX_VALUE. The minimum value that it can store is given by (Name of data type).MIN_VALUE.
How to Get Size, Minimum, and Maximum Value of Data Types in Java? The size of a data type is given by (name of datatype).SIZE. The maximum value that it can store is given by (Name of data type).MAX_VALUE.
Python list requires minimum 64 bytes on 32-bit / 64-bit system. It may vary as per hardware.
sizeof
is only going to work on value types.
For a string, you won't know the actual byte size until you populate it.
If you are set on doing this, serialize the list and measure it then. While not a guaranteed way, it is probably better than the alternative. Scratch that. It won't get you what you want without some real effort, if at all. You could perform a quick and dirty count like so:
public int getListSize()
{
Type type = typeof(T);
if (type.IsEnum)
{
return this.Sum(item => Marshal.SizeOf(Enum.GetUnderlyingType(type)));
}
if (type.IsValueType)
{
return this.Sum(item => Marshal.SizeOf(item));
}
if (type == typeof(string))
{
return this.Sum(item => Encoding.Default.GetByteCount(item.ToString()));
}
return 32 * this.Count;
}
If you really want to know more about size, here is a comprehensive answer on the topic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With