Share via


Custom attribute - DateTime as attribute argument

Question

Monday, March 24, 2008 12:18 PM

I'm building a custom attribute. I want a DateTime value to be entered in the attribute as argument.

 How can I do this?

[MyAttribute(DateTime.Parse("24/3/2008"))]

Raises an error:

An attribute argument must be a constant expression, typeof expression or array creation expression

 

 

 

All replies (8)

Wednesday, March 26, 2008 2:41 AM ✅Answered

The problem is DateTime.Parse return a runtime object, while in attribute we need the parameter fixed at the compile-time.

The instance of an attribute class is constructed by the compiler when the compiler detects an attribute applied to the target, and initializes public fields and properties that have been specified. After that, the instance of the attribute is serialized to the target's metadata table entry.All these are done by the compiler and there is not a way to get any runtime variable.

Thanks


Thursday, March 27, 2008 3:26 PM ✅Answered

A const one will do.

You cant have a constant datetime!!  I think the only option is to use a string! 


Monday, March 24, 2008 12:29 PM

Have you tried new DateTime(..?


Monday, March 24, 2008 12:59 PM

That does not work....

 


Monday, March 24, 2008 8:53 PM

Hi Johan,

Please could you paste the MyAttribute class please?

Thanks,

 


Tuesday, March 25, 2008 4:57 AM

using System;

using System.Diagnostics;

/// <summary>

/// Custom attribute for class documentation

/// </summary>

[AttributeUsage(AttributeTargets.Class)]

public class DocumentationAttribute : Attribute

{

private AuthorNames _lastAuthorName;

private DateTime _lastChangeDate;

public DocumentationAttribute(AuthorNames authorName, DateTime lastChangedate)

{

this.LastAuthorName = authorName;

this.LastChangeDate = lastChangedate;

}

public AuthorNames LastAuthorName

{

get

{

return _lastAuthorName;

}

set

{

_lastAuthorName = value;

}

}

public DateTime LastChangeDate

{

get

{

return _lastChangeDate;

}

set

{

_lastChangeDate = value;

}

}

}

 


Wednesday, March 26, 2008 3:33 AM

So I cannot work with DateTime type? Use a string instead?


Thursday, March 27, 2008 5:22 AM

A const one will do.

Thanks.