0

I have the following scenario:

/* Attribute to be filled */
public class Flower
{
    public FlowerType Type { get; set; }

    public string Value { get; set; }
}

public enum FlowerType 
{
    Rose,
    Daisy,
    Tulip
}

[AttributeUsage(AttributeTargets.Class)]
public sealed class FlowerAttribute : Attribute
{
    public string FlowerValue { get; }

    public FlowerAttribute(string flowerValue)
    {
        FlowerValue = flowerValue;
    }
}

What I am trying to achieve is a way to give the class Flower an attribute depending on runtime, meaning that if the flower will be instantiated as a Rose type, then the attribute on top of Flower will have the FlowerValue set to "Rose". Can I achieve this somehow? Thanks as always in advance!

Corentin Pane
  • 4,794
  • 1
  • 12
  • 29
Tarta
  • 1,729
  • 1
  • 29
  • 63
  • It´s not clear to me what you want to achieve by this. Attributes are clearly something you directly bake into your assembly at compile-time. Thus I assume you don´t attributes at all. So please clearify why you think you need them in the first place. – MakePeaceGreatAgain Nov 13 '19 at 14:16
  • 1
    Maybe this can help: https://stackoverflow.com/questions/14663763/how-to-add-an-attribute-to-a-property-at-runtime – Andrei Codreanu Nov 13 '19 at 15:12

1 Answers1

3

Can I achieve this somehow?

No. Attribute arguments are always decided at compile-time - that's why they have to be compile-time constants. The values are baked into the IL.

It's not clear what the bigger goal is here, but anything dynamic is unlikely to be a good fit for attributes.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194