find all const short variables on a static class in csharp

You can use reflection to get all the fields of a static class and then filter only the ones that are constants and have the type short. Here's some sample code:

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

public static class MyStaticClass
{
    public const short FirstNumber = 1;
    public const short SecondNumber = 2;
    public static readonly int NotAConstant = 3;
}

public class Program
{
    public static void Main()
    {
        var constantShorts = typeof(MyStaticClass)
            .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
            .Where(field => field.IsLiteral && field.FieldType == typeof(short))
            .Select(field => field.GetValue(null))
            .Cast<short>();

        foreach (var constant in constantShorts)
        {
            Console.WriteLine(constant);
        }
    }
}
715 chars
28 lines

In this example code, MyStaticClass has two constant short variables FirstNumber and SecondNumber, and one readonly int variable. The Main method uses reflection to find the constant shorts and prints their values to the console.

The output of running this code would be:

main.cs
1
2
4 chars
3 lines

gistlibby LogSnag