Question: Generic methods should provide type parameter

"Generic methods should provide type parameter"

http://www.gotdotnet.com/team/fxcop/docs/rules.aspx?version=1.32&url=/Design/GenericMethodsShouldProvideTypeParameter.html

public sealed class ReflectionAgent
{
public static T GetCustomAttribute<T>(MemberInfo memberInfo)
{
if (memberInfo == null) return default(T);
object[] attributes = memberInfo.GetCustomAttributes(typeof(T), true);
return ((attributes != null) && (attributes.Length == 1)) ? (T)attributes[0] : default(T);
}
}

I want to call it like this

PropertyInfo propInfo = typeof(TestClass).GetProperty("FirstName");
ItemTypeAttribute attr =
ReflectionAgent.GetCustomAttribute<ItemTypeAttribute>(propInfo);

TIA

Robert Zurer

[1092 byte] By [bzurer] at [2008-2-21]
# 1

I'm not sure why you are pointing to the FxCop rule you've listed. The FxCop rule has nothing to do with what you are trying to do. Instead it relates to the idea that the Generic's type arguments should provide details about the method's parameters. For instance:

public static void SomeMethod<T>(T someParameter)

In your case, the return type is what you are determing with your generic type argument, so, while you are "breaking" this rule, this is a valid use of generics.

Onward to your example, however. This seems to work for me with the following code:



public class TestClass
{
[
XmlElement("Test")]
public string FirstName
{
get { return "Tobin"; }
}
}
static void Main(string[] args)
{
PropertyInfo propInfo = typeof(TestClass).GetProperty("FirstName");
XmlElementAttribute attr =
ReflectionAgent.GetCustomAttribute<XmlElementAttribute>(propInfo);
Console.WriteLine(attr.ElementName );
Console.ReadLine();
}
public class ReflectionAgent
{
public static T GetCustomAttribute<T>(MemberInfo memberInfo)
{
if (memberInfo == null) return default(T);

object[] attributes = memberInfo.GetCustomAttributes(typeof(T), true);
return ((attributes != null) && (attributes.Length == 1)) ?
(T)attributes[0] :
default(T);
}
}



Keep in mind that this can break fairly easily if someone passes in a value type or a non-attribute. You might want to constrain your generic by using the "where" keyword. For instance:



public
static T GetCustomAttribute<T>(MemberInfo memberInfo) where T : System.Attribute

Let me know if this helps.
TobinTitus at 2007-9-8 > top of Msdn Tech,Visual C#,Visual C# Language...
# 2
Thankyou very much for your response. I knew the code worked, I just wanted to make sure I wasn't missing something in the FxCop warning.
bzurer at 2007-9-8 > top of Msdn Tech,Visual C#,Visual C# Language...