C# Extension Method: Object - GetCustomAttribute

CSharp · Console

/Program.cs

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

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

        //C# Extension Method: Object - GetCustomAttribute
        var result1 = thisClass.GetCustomAttribute<MyTestAttribute>();
        var result2 = thisClass.GetCustomAttribute<MyTestAttribute>(false);
        var result3 = thisClass.GetType().GetCustomAttribute<MyTestAttribute>();
        var result4 = thisClass.GetType().GetCustomAttribute<MyTestAttribute>(false);
        var result5 = thisClass.GetCustomAttribute(typeof(MyTestAttribute));
        var result6 = thisClass.GetCustomAttribute(typeof(MyTestAttribute), false);
        var result7 = thisClass.GetType().GetCustomAttribute(typeof(MyTestAttribute));
        var result8 = thisClass.GetType().GetCustomAttribute(typeof(MyTestAttribute), false);
        var result9 = thisEnum.GetCustomAttribute<MyTestAttribute>();
        var result10 = thisEnum.GetCustomAttribute<MyTestAttribute>(false);
        var result11 = thisEnum.GetCustomAttribute(typeof(MyTestAttribute));
        var result12 = thisEnum.GetCustomAttribute(typeof(MyTestAttribute), false);

        Console.WriteLine(result1.Text);
        Console.WriteLine(result2.Text);
        Console.WriteLine(result3.Text);
        Console.WriteLine(result4.Text);
        Console.WriteLine(((MyTestAttribute)result5).Text);
        Console.WriteLine(((MyTestAttribute)result6).Text);
        Console.WriteLine(((MyTestAttribute)result7).Text);
        Console.WriteLine(((MyTestAttribute)result8).Text);
        Console.WriteLine(result9.Text);
        Console.WriteLine(result10.Text);
        Console.WriteLine(((MyTestAttribute)result11).Text);
        Console.WriteLine(((MyTestAttribute)result12).Text);
	}
}

[AttributeUsage(AttributeTargets.All)]
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
}
;