Home > database >  Get attribute information from inheriting class, inside static function
Get attribute information from inheriting class, inside static function

Time:10-08

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

CodePudding user response:

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;
    }
}

CodePudding user response:

Alternatively (and I'm just copy/pasting Mathias' code into another form syntactically here) if you really need to have the method static because you don't want to create an instance, you can add the following method to your attribute code (or any other static class, but I like to put it there with the attribute):

public static string GetFrom<T>()
{
    return GetFrom(typeof(T));
}

public static string GetFrom(Type t)
{
    var attribute = Attribute.GetCustomAttribute(t, typeof(VehicleShapeAttribute)) as VehicleShapeAttribute;

    if(attribute is VehicleShapeAttribute){
        return attribute.Shape;
    }

    return null;
}

Then you could write code like:

var shape = VehicleShapeAttribute.GetFrom<VauxhaulAstraSedan>();

or

var shape = VehicleShapeAttribute.GetFrom(typeof(VauxhaulAstraSedan));

or even

var vehicle = new VauxhaulAstraSedan();
var shape = VehicleShapeAttribute.GetFrom(vehicle.GetType());
  • Related