Search code examples
c#attributesmethodinfo

Setting methodInfo.IsDefined() to true with C#


I have a methodInfo from mymethod method of Example class.

internal class Example
{
    public static void mymethod(string str1, ref string str2, out string str3)
    {
        ....


MethodInfo mm = typeof(Example).GetMethod("mymethod");

How can I make an attribute (for example, ABCAttribute) of mm so that

mm.IsDefined(typeof(ABCAttribute), true)

becomes true?


Solution

  • You need to define your attribute.

    [AttributeUsage(AttributeTargets.Method)]
    public class ABCAttribute : Attribute
    {
    }
    

    Then apply it to your method.

    internal class Example
    {
        [ABC]
        public static void mymethod(string str1, ref string str2, out string str3)
        {
        }
    }