Annotation to force explicit typing for certain classes?

In general we are in favor of implicit typing of local variables (i.e. using “var”), so our configuration of Resharper is adapted to suggest changing explicitly typed local variables to implicitly typed if possible.

We do also have some classes with generic type parameters that we've specifically introduced to enforce static type safety, i.e.: make sure that the compiler raises an error when they are inadvertently mixed. Is there a way where we can annotate these classes such that Resharper will complain if they are implicitly typed somewhere?

Consider the following example:

class Foo
{}

class Bar
{}

class MyTypeSafeClass<T>
{
    public readonly int TypeSafeValue;
    public MyTypeSafeClass(int value)
    {
        TypeSafeValue = value;
    }
}

MyTypeSafeClass<Bar> CreateList(int value)
{
    return new MyTypeSafeClass<Bar>(value);
}

When variables of type MyTypeSafeClass<T> are explicitly declared, a compilation error occurs when types are inadvertently mixed.

void ExplicitlyTyped()
{
    // Expect a MyTypeSafeClass<Bar>, receives MyTypeSafeClass<Bar> -> OK
    MyTypeSafeClass<Bar> bar = CreateList(5);
    // Expect a MyTypeSafeClass<Foo>, receives MyTypeSafeClass<Bar> -> Compilation Error (OK)
    MyTypeSafeClass<Foo> foo = CreateList(42);
}

When using implicit typing however, there is no compilation error:

void ImplicitlyTyped()
{
    // Implicitly expect a MyTypeSafeClass<Bar>, receives MyTypeSafeClass<Bar> -> OK
    var implicitBar = CreateList(5);
    // Implicitly expect a MyTypeSafeClass<Foo>, receives MyTypeSafeClass<Bar> -> No Compilation Error (Potential Bug)
    var implicitFoo = CreateList(42);
}

Is there a way to enforce a Resharper warning when explicit typing for MyTypeSafeClass<T> is not used, while allowing implicit typing for other cases (where it would make sense)?

0
1 comment

Hello Bram,

thank you for sharing you case.

Unfortunately, ReSharper doesn't have functionality that could support such behavior.

 

0

Please sign in to leave a comment.