So first I have generic class that implement something.
public class MyGenericClass<T> where T : class
{
...
public T SomeFunction(T t) {...}
...
}
Then I want to have two "instance" of this generic class (with different type) that can be used everywhere in my project and don't know how to do that.
Use global might be one option, but I want to make another static class that contains different generic class.
public static class CosmosDBHelper
{
public static MyGenericClass<T1> t1;
public static MyGenericClass<T2> t2;
}
But the StyleCop will report error by SA1401 "Field should be private". I found the following solution, but it looks quite redundant.
public static class CosmosDBHelper
{
private static MyGenericClass<T1> t1;
public static MyGenericClass<T1> T1 { get { return t1; } }
private static MyGenericClass<T2> t2;
public static MyGenericClass<T2> T2 { get { return t2; } }
}
Is there a better way?
Thanks,
This has nothing to do with using a generic class in a static class. The rule SA1401 simply states that class fields should not be public.
Reading the documentation, we find that "a violation of this rule occurs whenever a field in a class is given non-private access. For maintainability reasons, properties should always be used as the mechanism for exposing fields outside of a class, and fields should always be declared with private access. This allows the internal implementation of the property to change over time without changing the interface of the class."
There are two solutions:
private static MyGenericClass<T1> t1;
private static MyGenericClass<T2> t2;
public static MyGenericClass<T1> t1 { get; } // Add a set to make it writeable
public static MyGenericClass<T2> t2 { get; }
Or, if needed, a combination of the two (where the private field is a backing field for the public property, as you have in your solution).
Also, just to be clear, the types passed to MyGenericClass
must be defined when creating field or property based on them. The properties t1
and t2
should be of specific, different types, and should be declared as such:
public static MyGenericClass<SomeClass> MyCustomClassInstance { get; }
public static MyGenericClass<string> MyStringClassInstance { get; }