Soath
Soath

Reputation: 33

How to bypass the need of specifing a generic parameter type?

I have an extension method like this one :

      public static void ImplementsAttribute<TX, TY>(this Expression<Func<TY>> expression) 
     where TX : Coupling.PropertiesMergerAttribute
  {
     var memberExpression = expression.Body as MemberExpression;
     var name = MetaHelper.GetPropertyName(expression);
     var property = memberExpression.Expression.Type.GetProperty(name);
     var attributes = property.GetCustomAttributes(true);
     Assert.IsTrue(attributes.Any(a => a is TX));
  }

I can actually use my code like this :

     Expression<Func<String>> nameProperty = () => new ImprovisedExplosiveXML().Name;
     nameProperty.ImplementsAttribute<Coupling.UnresolvablePropertiesMergerAttribute, String>();

but I would like to not need to specify the second generic parameter type :

     Expression<Func<String>> nameProperty = () => new ImprovisedExplosiveXML().Name;
     nameProperty.ImplementsAttribute<Coupling.UnresolvablePropertiesMergerAttribute>();

Is there a way of doing this in C# 3.5 ?

Upvotes: 2

Views: 350

Answers (2)

Tejs
Tejs

Reputation: 41266

You can do something like this:

public class AttributeTester
{
    public Attribute[] Attributes { get; set; }

    public void ImplementsAttribute<TAttType>()
    {
         Assert.IsTrue(Attributes.Any(x => x is TAttType));
    }
}

public static void ForProperty<TType, TProperty>(this TType obj, Expression<Func<TType, TProperty>> expression)
{
     var memberExpression = expression.Body as MemberExpression;
     var name = MetaHelper.GetPropertyName(expression);
     var property = memberExpression.Expression.Type.GetProperty(name);
     return new AttributeTester { Attributes = property.GetCustomAttributes(true) };
}

Then, you should be able to just write it like so:

new ImproveisedExplosiveXML().ForProperty(x => x.Name).ImplementsAttribute<SomeAttribute>();

Upvotes: 0

RichK
RichK

Reputation: 11879

C# does not support partial generic inference. If the compiler can't determine all the types you have to supply them all yourself.

Upvotes: 2

Related Questions