Attributes with multiple objects as param for constructor


T

ThisBytes5

I am using an attribute on the properties of my object to help with
parsing of data. The attribute will determine if the current property
is to be populated based on the version of the data. As such I need to
be able to create the attribute with the version and some other values
for the version. So I tried the following (typed for the example, not
the actual code).

defined the constructor for the Attrib as:
public MyAttrib(params object[] versions)

and defined the class as:
public MyClass
{
private string prop1;

[MyAttribute(new VersionInfo("1.0", "Description"), new
VersionInfo("2.0", "Description"))]
public string Prop1
{
get { return prop1; }
set { prop1 = value; }
}
}

The class fails to compile with the follwoing error:
An attribute argument must be a constant expression, typeof
expression or array creation expression

Have I defined something incorrectly? Is this sort of thing supported
at all in Dot net?

If it can't be done as described above, any suggestion on how to
accomplish the desired task?

Thanks
 
Ad

Advertisements

M

Mattias Sjögren

Have I defined something incorrectly? Is this sort of thing supported
at all in Dot net?

Not the way you want it, no. Have you considered using multiple
attribute instances instead, one per VersionInfo?


public MyAttribute(string versionNumber, string description)

....

[MyAttribute("1.0", "Description"), MyAttribute("2.0", "Description")]
public string Prop1



Mattias
 
G

Guest

Attributes are evaluated at compile-time, so values must be able to evaluate
to compile-time constants.

You are creating an object with a dynamic allocation operator ("new"). This
is only supported at run-time, so cannot be compiled. If you change your
attribute to take version string constants and create the VersionInfo objects
at run-time (when you'll really use them), you will probably have better luck.

-dM
 
Ad

Advertisements

T

ThisBytes5

I had trid this in the past, but assumed it wouldn't work as I got an
error of multiple attributes defined. Today I hit F1 on the error and
saw I can specify that I want to allow multiples. Set that to true and
it all works!!!

Thanks
Wayne

Have I defined something incorrectly? Is this sort of thing supported
at all in Dot net?

Not the way you want it, no. Have you considered using multiple
attribute instances instead, one per VersionInfo?


public MyAttribute(string versionNumber, string description)

...

[MyAttribute("1.0", "Description"), MyAttribute("2.0", "Description")]
public string Prop1



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top