Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you have init-once variables in C# extension methods?

Extension methods operate on an instance of a class, but they are implemented as static methods inside a static class. It seems that they don’t allow declaring any variables static or readonly.
Here is an artificial example that illustrates the problem. How can I code this so that scammers is initialized only once?

sealed class Caller // can't be modified
{
    public long Phone { get; set; }
}

static class Validator
{
    public static Caller Validate(this Caller caller)
    {
        // I want to initialize this only once from a more elaborate source
        HashSet<long> scammers = new() { 2345678901, 3456789012, 4567890123 };

        if (scammers.Contains(caller.Phone)) throw new ArgumentException("known scammer");
        return caller;
    }
}

EDIT:
I can see that moving the declaration of scammers out of the method solves the init-once problem. The reason I didn’t think of it is because my Validate(...) method is actually generic Validate<T>(...) and the variable needs to be generic with the same type.
Looks like I need to break the Validator class apart and put the generic methods in a separate class that itself is generic with Type T.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think I’m missing something in your question… because extension classes do support static variables.

This works just fine (tested in .NET 4.7.2 and .NET 8, it’s not an old version thing…):

sealed class Caller // can't be modified
{
    public long Phone { get; set; }
}

static class Validator
{
    private static HashSet<long> scammers = new HashSet<long>() { 2345678901, 3456789012, 4567890123 };
    
    public static Caller Validate(this Caller caller)
    {
        if (scammers.Contains(caller.Phone)) throw new ArgumentException("known scammer");
        return caller;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading