I am trying to implement an extension for any c# object using extensions.
My method will use an object X that I cannot modify and takes the type of the object as an argument. Problem is I want to keep this object; I don't want it to be garbage-collected.
This is my current code, but I cannot declare an extension method in a non-generic static class (Extensions_S<T>
is NOT allowed. Compiler's error message is "extension method must be defined in a non-generic static class").
namespace Lib
{
public static class Extensions_S<T>
{
private static X generateA_X = null;
public static A generateA<T>(this T value)
{
if (generateA_X == null)
generateA_X = new X(typeof(T));
return generateA_X.from(value);
}
}
}
generateA_X
is a actually the equivalent of a static method variable. I want a different instance for each type T which calls this extension method.
This is why I am trying to make Extensions_S
generic.
My question is: Is there a workaround?