Reputation: 17
Here is my piece of code where I am calling PageObjectBase generic class property to return the instance. This works fine, but when I run the code analysis getting following errors:
CA1000 Remove 'PageObjectBase<T>.PageObject' from 'PageObjectBase<T>' or make it an instance member
CA1000 Remove 'PageObjectBase<T>.InstanceCreation()' from 'PageObjectBase<T>' or make it an instance member
How could I resolve this error without affecting TestBase and the logic implemented in PageObjectBase?
public class TestBase
{
public T NavigateToScreenandReturnPageObject<T>() where T :class, new()
{
return PageObjectBase<T>.PageObject;
}
}
public static class PageObjectBase<T> where T : class, new()
{
private static T singleTonObject;
public static T PageObject
{
get
{
return InstanceCreation();
}
}
public static T InstanceCreation()
{
if (singleTonObject == null)
{
singleTonObject = new T();
}
return singleTonObject;
}
}
Upvotes: 1
Views: 654
Reputation: 5624
The reason for this is that a static member in a generic type will not be shared among instances of different close constructed types. This means that for a generic class MyGeneric<T>
which has public static string MyProp { get; set; }
, the values of MyGeneric<int>.MyProp
and MyGeneric<string>.MyProp
have completely different, independent values.
In most of the cases these may cause runtime errors and that's why code analysis provides suggestion to avoid it.
If you still want to keep the static members on the type and keep the code analysis rule , the. I would suggest to create a non generic base class for T type of types and have static method there.
Upvotes: 0
Reputation: 4059
There isn't anything to fix here based on those warnings. Those warnings are aimed at people that misuse static variables in generic classes while not realizing that each generic type produces a different static variable. Your code is actually taking advantage of how static variables work in generic classes.
I would also definitely recommend you read the link Alexei recommended to fix up your singleton implementation. http://csharpindepth.com/Articles/General/Singleton.aspx
Upvotes: 1