Reputation: 11357
I'm using Microsoft.CodeAnalysis.FxCopAnalyzers
and the CA1000
rule says the following.
Do not declare static members on generic types.
How to fix violations
To fix a violation of this rule, remove the static member or change it to an instance member.
When to suppress warnings:
Do not suppress a warning from this rule. Providing generics in a syntax that is easy to understand and use reduces the time that is required to learn and increases the adoption rate of new libraries.
My code is the following. The Success
method is the one which triggers the rule.
public class ResultResponse
{
internal ResultResponse(bool isSuccess)
{
IsSuccess = isSuccess;
}
public bool IsSuccess { get; }
public static ResultResponse Failed()
=> new ResultResponse(false);
}
public class ResultResponse<T> : ResultResponse
{
internal ResultResponse(T value, bool isSuccess)
: base(isSuccess)
{
Value = value;
}
public T Value { get; }
public static ResultResponse<T> Success(T value)
=> new ResultResponse<T>(value, true);
}
I can make the constructor public and use it in the example above but I also have the case that I want to keep the constructor internal to ensure the type is used correctly.
Is moving the Success
method to the non generic type the correct aproach?
public class ResultResponse
{
internal ResultResponse(bool isSuccess)
{
IsSuccess = isSuccess;
}
public bool IsSuccess { get; }
public static ResultResponse Failed()
=> new ResultResponse(false);
public static ResultResponse<T> Success<T>(T value)
=> new ResultResponse<T>(value, true);
}
public class ResultResponse<T> : ResultResponse
{
internal ResultResponse(T value, bool isSuccess)
: base(isSuccess)
{
Value = value;
}
public T Value { get; }
}
Upvotes: 8
Views: 2999
Reputation: 239636
Is moving the
Success
method to the non generic type the correct aproach?
It's a decent approach. Note that now, you can call:
ResultResponse.Success(someat);
And the compiler will infer the generic type from someat
. In your previous code, because you were calling the static
method in the generic, you'd always have had to ("redundantly") specify the type parameter:
ResultResponse<int>.Success(someat);
Upvotes: 6