Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access "this" inside of static codeblocks

Tags:

c#

static

grammar

Lately I've found myself writing alot of classes similar to:

public class MyTypeCodes
{
    public static MyTypeCode E = new MyTypeCode{ Desc= "EEE", Value = "E" };
    public static MyTypeCode I = new MyTypeCode { Desc= "III", Value = "I" };

    private static readonly Lazy<IEnumerable<MyTypeCode>> AllMyTypeCodes =
        new Lazy<IEnumerable<MyTypeCode>>(() =>
        {
            var typeCodes = typeof(MyTypeCodes)
                 .GetFields(BindingFlags.Static | BindingFlags.Public)
                 .Where(x => x.FieldType == typeof (MyTypeCode))
                 .Select(x => (MyTypeCode) x.GetValue(null))
                 .ToList();

                 return typeCodes;
        });

    public static IEnumerable<MyTypeCode> All
    {
        get { return AllMyTypeCodes.Value; }
    }
}

If you notice inside of new Lazy<IEnumerable<MyTypeCode>>(() => that I specifically need to do typeof(MyTypeCodes) even though I'm inside of class MyTypeCodes. Is there any way I can write this without specifically need to call typeof() for the class i'm specifically inside of? If this was a regular method I would this.GetType() which obviously doesn't work (for some reason) with statics.

like image 280
Chris Marisic Avatar asked May 22 '26 12:05

Chris Marisic


1 Answers

Is there any way I can write this without specifically need to call typeof() for the class i'm specifically inside of?

No, this is likely the best option. If you know you are never going to add any other fields, of any other types, you can just skip the Where clause.

In addition, you should use ToList() to prevent the IEnumerable<T> generated from having to rerun each time it's enumerated:

private static readonly Lazy<IEnumerable<MyTypeCode>> AllMyTypeCodes =
    new Lazy<IEnumerable<MyTypeCode>>(() =>
    {
        return typeof(MyTypeCodes)
             .GetFields(BindingFlags.Static | BindingFlags.Public)
             // If you're not using any other fields, just skip this
             // .Where(x => x.FieldType == typeof (MyTypeCode ))
             .Select(x => (MyTypeCode) x.GetValue(null))
             .ToList();                 
    });
like image 76
Reed Copsey Avatar answered May 25 '26 00:05

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!