C# Extension Method: Object - GetCustomAttributesByFullName

CSharp · Console

/Program.cs

// C# Extension Method
// Doc: https://csharp-extension.com/en/method/1002725/object-getcustomattributesbyfullname

// @nuget: Z.ExtensionMethods
using System;
					
public class Program
{
	public static void Main()
	{
        var thisClass = new MyTestClass();
        var thisEnum = MyTestEnum.Test;

        //C# Extension Method: Object - GetCustomAttributesByFullName				
		var result1 = thisClass.GetCustomAttributesByFullName("MyTestAttribute");
        var result2 = thisClass.GetCustomAttributesByFullName("MyTestAttribute", false);
        var result3 = thisClass.GetType().GetCustomAttributesByFullName("MyTestAttribute");
        var result4 = thisClass.GetType().GetCustomAttributesByFullName("MyTestAttribute", false);
        var result5 = thisEnum.GetCustomAttributesByFullName("MyTestAttribute");
        var result6 = thisEnum.GetCustomAttributesByFullName("MyTestAttribute", false);

        Console.WriteLine(((MyTestAttribute) result1[0]).Text);
        Console.WriteLine(((MyTestAttribute) result2[0]).Text);
        Console.WriteLine(((MyTestAttribute) result3[0]).Text);
        Console.WriteLine(((MyTestAttribute) result4[0]).Text);
        Console.WriteLine(((MyTestAttribute) result5[0]).Text);
        Console.WriteLine(((MyTestAttribute) result6[0]).Text);
	}
}

[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class MyTestAttribute : Attribute
{
    public string Text;

    public MyTestAttribute(string text)
    {
        Text = text;
    }
}

[MyTest("Test Class")]
public class MyTestClass
{
}

public enum MyTestEnum
{
    [MyTest("Test Enum")]
    Test
}
;