momo
momo

Reputation: 33

How to resolve warning

I have:

Warning Type parameter 'TFrom' has the same name as the type parameter from outer type

     private class InnerExpressionTransformer<TFrom, TTo> : ExpressionVisitor
        where TTo : TFrom
    {
        private ParameterExpression _parameter;

        public InnerExpressionTransformer()
        {
            _parameter = Expression.Parameter(typeof(TTo));
        }
    }

How do I resolve this?

Upvotes: 0

Views: 227

Answers (1)

David
David

Reputation: 10708

As the warning states, you have a type parameter with the same name. This is a warning because nested classes share the generic paraneters of their parent type - you must reference Outer<Paraneter>.Inner. Because of this, the names can collide, and because of that, any usage of that type parameter will use the inner definition, thus hiding the outer parameter. While this might be intended behaviour, it could result in a nasty gotcha should you try to reference the outer.

There are two way to resolve this, the first and foremost being to make sure you need that inner type. If you're simply restating the outer generic, it's completely unnecessary, and can be done away with; even constraints such as TTo : TFrom will work if TFrom is a generic parameter of the outer class. Thus:

public class ExpressionTransformer<TFrom>
{
    // ...
    private class InnerExpressionTransformer<TTo>
        where TTo : TFrom
    {
        // ...
    }
}

The second method, should the inner parameter be necessary, is simply renaming one of the parameters, usually the inner one. Since this is a private class, it's easiest to change it there, such as to TFromInner.

Upvotes: 1

Related Questions