Mobz
Mobz

Reputation: 374

C#: Get name of Static Members

public class MyClass
{
    public static MyClass A = new MyClass();
    public static MyClass B = new MyClass();
    public static MyClass C = new MyClass();

    public static IEnumerable<MyClass> List() => new[] {A,B,C };
}

Calling this code:

foreach (var item in MyClass.List())
{
    Debug.Print(nameof(item));
}

..will return:

item
item
item

But I want it to show this instead:

A
B
C

How can I make that happen?

--Edit-- #Sinatr in the comment give a good fairly simple suggestion using a Dictionary instead

public static Dictionary<MyClass, string> List()
{
    return new Dictionary<MyClass, string>()
    {
            { A, nameof(A) },
            { B, nameof(B) },
            { C, nameof(C) },
    };
} 

Upvotes: 2

Views: 524

Answers (1)

Amal K
Amal K

Reputation: 4929

There are two options I can think of at the moment:

1. Use System.Reflection

typeof(MyClass)
    .GetFields(BindingFlags.Static | BindingFlags.Public)
    .Select(field => field.Name)
    .ToList()
    .ForEach(Console.WriteLine);

2. Add a companion method

As hinted in the comments, add a companion method to List() like ListNames() that returns an IEnumerable of names:

public class MyClass
{
    public static MyClass A = new MyClass();
    public static MyClass B = new MyClass();
    public static MyClass C = new MyClass();

    public static IEnumerable<MyClass> List() => new[] {A, B, C };
    public static IEnumerable<MyClass> ListNames() => new[] 
    {
        nameof(A), 
        nameof(B), 
        nameof(C) 
    };

}

Upvotes: 4

Related Questions