Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get byte size of type in generic list?

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?

like image 575
Safran Ali Avatar asked Aug 31 '11 10:08

Safran Ali


People also ask

How to print the size and value of the byte?

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.

How do you find the size of a data type?

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 and maximum value of data types in Java?

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.

What is the minimum size of list in Python?

Python list requires minimum 64 bytes on 32-bit / 64-bit system. It may vary as per hardware.


1 Answers

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.

like image 90
Paul Walls Avatar answered Oct 06 '22 01:10

Paul Walls