-1

I am loooking for an elegant way to set the value of DateTime.Now as value of an Attribute.

I have this code:

    [MyValue(DateTime.Now)]
    public DateTime? VertragDatum { get; set; }

But I am getting a syntax error and tells me that the Type DateTime is not a valid attribute parameter type. Do you have any idea how to can achieve that?

My implementation:

public class MyValueAttribute : Attribute
{
    public string MyValue { get; }

    public MyValueAttribute(DateTime myValue)
    {
        MyValue = myValue.ToString();
    }
}
user9923760
  • 596
  • 2
  • 8
  • 18
  • when do you want that value set? on object creation, on type initialization? sounds like an xy problem here. – Daniel A. White Aug 06 '19 at 14:21
  • Please note, that `DateTime.Now` will be set at *compile time* (e.g. `6 Aug 2019 17:21:05`) and be read at *runtime* (say somewhen at `14 Oct 2019 14:52:47`). Do you really want such behavior? – Dmitry Bychenko Aug 06 '19 at 14:21
  • Following on with what @dymanoid says, the only thing you can use as a constructor parameter for an attribute is a constant expression. C# has no constant or literal `DateTime`s (unlike VB). If it's always `DateTime.Now`, you can set it in the constructor. But, not only will `DateTime.Now` not work where it is, no DateTime expression will. – Flydog57 Aug 06 '19 at 14:23
  • You can potentially create a "fody" weaver to inject the current date-time in as a string or some sort of roslyn based plugin. I suspect that's outside the scope of what users want for this question. – Glenn Watson Aug 06 '19 at 14:30
  • Possible duplicate of [How to pass objects into an attribute constructor](https://stackoverflow.com/questions/1235617/how-to-pass-objects-into-an-attribute-constructor) – Glenn Watson Aug 06 '19 at 14:33

2 Answers2

-1

DateTime isn't a supported type.

As referenced here valid types are:

The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:

  • One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort.
  • The type object.
  • The type System.Type.
  • An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (Attribute specification).
  • Single-dimensional arrays of the above types.
  • A constructor argument or public field which does not have one of these types, cannot be used as a positional or named parameter in an attribute specification.
Glenn Watson
  • 2,758
  • 1
  • 20
  • 30
-2

specs says:

The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:

One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort.

Antoine V
  • 6,998
  • 2
  • 11
  • 34