oscilatingcretin
oscilatingcretin

Reputation: 10959

Object initializer for attributes?

I have the following attribute in which I pass types to the constructor:

[DataTypeConversion(typeof(StringToBoolConverter), typeof(BoolToYesNoConverter))]

However, I'd really like to ditch the constructor and force the object setup through an initializer like so:

[DataTypeConversion{InConverterType = typeof(StringToBoolConverter), OutConverterType = typeof(BoolToYesNoConverter)}]

It doesn't appear that I can do this, though. Is there another way or is it simply not supported with attributes?

Edit: Why do I want to do this? It's not just improve readability, but it will also force the developer to specify a property. While attributes support named constructor arguments, they're optional.

Edit2: I can instantiate an attribute like this:

var attr = new DataTypeConversionAttribute
{
    InConverterType = typeof(StringToBoolConverter),
    OutConverterType = typeof(BoolToYesNoConverter)
};

I want to be able to instantiate it the same way when decorating a property.

Update

astef provided the correct answer. Here's my attribute:

[AttributeUsage(AttributeTargets.Property)]
public class DataTypeConversionAttribute : Attribute
{
    public Type InConverterType { get; set; }

    public Type OutConverterType { get; set; }
}

While {} are used for object initializers in standard code, you need to use () for attributes like so:

public class MyClass
{
    [DataTypeConversion(InConverterType = typeof(StringToBoolConverter), OutConverterType = typeof(BoolToYesNoConverter))]
    public bool MyBool { get; set; }
}

Upvotes: 1

Views: 545

Answers (2)

Jehof
Jehof

Reputation: 35564

It is not supported by the C#-Compiler for declaring Attributes on types using this style. Take a look at the MSDN how to use attributes.

Upvotes: 1

astef
astef

Reputation: 9518

Change it to:

[DataTypeConversion(InConverter = typeof(StringToBoolConverter), OutConverter = typeof(BoolToYesNoConverter))]

(brackets instead of braces)

I assume that DataTypeConversionAttribute has a default constructor and two public properties with public setters: InConverter and OutConverter with return type System.Type

Upvotes: 2

Related Questions