Search code examples
c#pythonevalgetattr

C# Get Access Properties


I would like to call function attribute (and also type) by it's name.

In python this goes something like this:

import time

method_to_call = getattr(time, 'clock') #  time.clock()
result = method_to_call()
print(result)

But what about C# and types? I want to use sizeof on converted ITEM_STRING_TO_TYPE. Is it even possible in C#?

List<string> mainList = new List<string>(new string[]
{
    "bool",
    "byte",
    "char",
    "decimal",
    "double",
    "float",
    "int",
    "long",
    "sbyte",
    "short",
    "uint",
    "ulong",
    "ushort"
});
foreach (string item in mainList)
{
    Console.WriteLine("Size of {0} : {1}", item, sizeof(ITEM_STRING_TO_TYPE));
    // like this
    Console.WriteLine("Size of int: {0}", sizeof(int));
}

Solution

  • if by ITEM_STRING_TO_TYPE, you mean a Type, then there are a few problems here:

    • the .NET API is mostly .NET-based; int, long etc are not .NET names - they are C# aliases (and .NET targets multiple languages); this means that you'd need a language-specific map between the alias and a Type (the .NET names here are System.Int32 and System.Int64 respectively)
    • sizeof cannot be used with a Type; there is Unsafe.SizeOf<T>(), but that also cannot be used directly with a Type - it requires generics, so you'd need reflection via MakeGenericMethod
    • put those together, and it really won't be worth it - you'd do better to just hard-code the values; or just use a tuple array:
    List<(string name, int size)> mainList = new List<(string,int)>(new []
        {
            ("bool", sizeof(bool)), 
            // ...
            ("ushort", sizeof(ushort)), 
        });
    

    then you can use:

    foreach (var item in mainList)
    {
        Console.WriteLine("Size of {0} : {1}", item.name,  item.size);
    }
    

    or:

    foreach ((var name, var size) in mainList)
    {
        Console.WriteLine("Size of {0} : {1}", name, size);
    }