create a float-based attribute that accepts modifiers to output a final value in csharp

To create a float-based attribute in C#, you can declare it as follows:

main.cs
[AttributeUsage(AttributeTargets.Property)]
public class MyFloatAttribute : Attribute
{
    private float _baseValue;
    
    public MyFloatAttribute(float baseValue)
    {
        _baseValue = baseValue;
    }

    public float GetValue(float modifier)
    {
        return _baseValue * modifier;
    }
}
307 chars
16 lines

This attribute takes a float value in the constructor, which serves as the base value. It also has a method called GetValue which accepts a modifier parameter that is used to output the final value.

To use this attribute, simply apply it to a property:

main.cs
class MyClass
{
    [MyFloat(10.0f)]
    public float MyProperty { get; set; }    
}
85 chars
6 lines

In this example, the MyProperty property has been decorated with the MyFloat attribute, and has a base value of 10.0f. To retrieve the final value, you would call GetValue on an instance of the attribute, passing in the modifier value:

main.cs
var myObject = new MyClass();
var attribute = (MyFloatAttribute)Attribute.GetCustomAttribute(typeof(MyClass).GetProperty("MyProperty"), typeof(MyFloatAttribute));
var finalValue = attribute.GetValue(2.0f); // finalValue would be 20.0f
235 chars
4 lines

In this example, finalValue is calculated by calling GetValue on the MyFloat attribute that is applied to the MyProperty property. The 2.0f value serves as the modifier.

gistlibby LogSnag