Search code examples
c#static-methodsdecorationattributeusage

Get attribute information from inheriting class, inside static function


I have a situation where I need to get the value on a property on an attribute (decorator) applied to a class. That class that is decorated, is inheriting from an abstract class. It is this abstract class that needs to get the attribute information, but it needs to do so inside a static function.

I cannot post the exact scenario, but here is a terrible example that could do without attributes, but please work with it as it is:

public class VehicleShapeAttribute : Attribute
{
    public string Shape { get; }
    public VehicleShapeAttribute(string shape)
    {
        Shape = shape;
    }
}

public abstract class Vehicle
{
    public string Brand { get; set; }
    public string Model { get; set; }
    public string Colour { get; set; }

    public static string GetVehicleShape()
    {
        //return value from the attribute, from this static function. CANT DO THIS HERE
        return AnyInheritingClass.VehicleShapeAttribute.Shape;
    }
}

[VehicleShape("sedan")]
public class VauxhaulAstraSedan : Vehicle
{
    //calling GetVehicleShape() on this class should automatically return "sedan"
}

Is this possible?

This is a bad example but I cannot post the actual code


Solution

  • Make the method non-static and resolve the runtime type with this.GetType():

    public abstract class Vehicle
    {
        public string Brand { get; set; }
        public string Model { get; set; }
        public string Colour { get; set; }
    
        public string GetVehicleShape()
        {
            var attribute = Attribute.GetCustomAttribute(this.GetType(), typeof(VehicleShapeAttribute)) as VehicleShapeAttribute;
    
            if(attribute is VehicleShapeAttribute){
                return attribute.Shape;
            }
    
            return null;
        }
    }
    

    For a static version, you'll need to accept a Vehicle parameter whose type you can then inspect:

    public static string GetVehicleShape(Vehicle vehicle)
    {
        var attribute = Attribute.GetCustomAttribute(vehicle.GetType());
        // ...