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. And that doesn't work because extension methods needs to be inside a non-generic static class...
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;
}
}