Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Attribute.GetCustomAttribute in .NET Core

I'm trying to convert the following method (which works fine in .NET Framework 4.6.2) to .NET Core 1.1.

public static TAttribute GetCustomAttribute<TAttribute>(MemberInfo member) where TAttribute : Attribute
{
    var attr = System.Attribute.GetCustomAttribute(member, typeof(TAttribute));
    if (attr is TAttribute)
       return attr;
    else
       return null;
}

This code is giving me the error

Attribute does not contain a definition for GetCustomAttribute.

Any idea what the .NET Core equivalent of this should be?

P.S. I tried the following but it seems to throw an exception. Not sure what the exception is because it just stops the app all together. I tried putting the code in a try catch block but still it just stops running so I couldn't capture the exception.

public static TAttribute GetCustomAttribute<TAttribute>(MemberInfo member) where TAttribute : Attribute
{
   var attr = GetCustomAttribute<TAttribute>(member);
   if (attr is TAttribute)
      return attr;
   else
      return null;
}
like image 780
Sam Avatar asked Apr 06 '17 06:04

Sam


People also ask

What is GetCustomAttribute in C#?

GetCustomAttribute(MemberInfo, Type) Retrieves a custom attribute applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for. GetCustomAttribute(Assembly, Type) Retrieves a custom attribute applied to a specified assembly.

How do I create a custom attribute in .NET core?

Declaring Custom AttributesWe can define an attribute by creating a class. This class should inherit from the Attribute class. Microsoft recommends appending the 'Attribute' suffix to the end of the class's name. After that, each property of our derived class will be a parameter of the desired data type.

What is AttributeUsage C#?

Determines how a custom attribute class can be used. AttributeUsage is an attribute that can be applied to custom attribute definitions to control how the new attribute can be applied. So it basically gives the compiler some extra information about the attribute class you will implement.


2 Answers

If you add a package reference to System.Reflection.Extensions or System.Reflection.TypeExtensions, then MemberInfo gets a lot of extension methods like GetCustomAttribute<T>(), GetCustomAttributes<T>(), GetCustomAttributes(), etc. You use those instead. The extension methods are declared in System.Reflection.CustomAttributeExtensions, so you'll need a using directive of:

using System.Reflection;

In your case, member.GetCustomAttribute<TAttribute>() should do everything you need.

like image 86
Marc Gravell Avatar answered Oct 25 '22 23:10

Marc Gravell


You need to use GetCustomAttribute method:

using System.Reflection;
...

typeof(<class name>).GetTypeInfo()
      .GetProperty(<property name>).GetCustomAttribute<YourAttribute>();
like image 41
Set Avatar answered Oct 26 '22 00:10

Set