find all variables of type const short on a static class in csharp

To find all the variables of type const short on a static class in C#, you can use reflection. Reflection allows you to examine the metadata of a class and access its properties and members at runtime. Here's an example code:

main.cs
using System;
using System.Linq;
using System.Reflection;

public static class MyClass
{
    public const short Var1 = 1;
    public const short Var2 = 2;
    public static short Var3 = 3;
}

class Program
{
    static void Main(string[] args)
    {
        Type staticClassType = typeof(MyClass);
        FieldInfo[] fields = staticClassType.GetFields(BindingFlags.Public | BindingFlags.Static);

        var constShortVariables = fields
            .Where(field => field.IsLiteral && field.FieldType == typeof(short))
            .Select(field => field.Name)
            .ToList();

        Console.WriteLine($"Const short variables in {staticClassType.Name}: {string.Join(", ", constShortVariables)}");
    }
}
714 chars
27 lines

In this example, we have a static class named MyClass with three variables: Var1 and Var2 of type const short, and Var3 of type static short.

We use the Type.GetFields method to get all the public static fields of the MyClass type. Then, we filter these fields by checking if they are const and short using the FieldInfo.IsLiteral and FieldInfo.FieldType properties.

Finally, we use LINQ to select the names of the constants, and output them to the console.

The output of this program will be:

main.cs
Const short variables in MyClass: Var1, Var2
45 chars
2 lines

gistlibby LogSnag