Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a collection initializer for an Attribute?

Can an attribute in C# be used with a collection initializer?

For example, I'd like to do something like the following:

[DictionaryAttribute(){{"Key", "Value"}, {"Key", "Value"}}]
public class Foo { ... }

I know attributes can have named parameters, and since that seems pretty similar to object initializers, I was wondering if collection initializers were available as well.

like image 543
Scott Rippey Avatar asked Aug 03 '11 20:08

Scott Rippey


People also ask

What is collection initializer?

C# - Object Initializer Syntax NET 3.5) introduced Object Initializer Syntax, a new way to initialize an object of a class or collection. Object initializers allow you to assign values to the fields or properties at the time of creating an object without invoking a constructor.

How do you initialize an object in C sharp?

In object initializer, you can initialize the value to the fields or properties of a class at the time of creating an object without calling a constructor. In this syntax, you can create an object and then this syntax initializes the freshly created object with its properties, to the variable in the assignment.

How are Initializers executed in C#?

Initializers execute before the base class constructor for your type executes, and they are executed in the order in which the variables are declared in your class. Using initializers is the simplest way to avoid uninitialized variables in your types, but it's not perfect.

What is initializer C#?

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements.


1 Answers

Update: I'm sorry I'm mistaken - pass array of custom type is impossible :(

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

  1. One of the following types: bool, byte, char, double, float, int, long, short, string.
  2. The type object.
  3. The type System.Type.
  4. An Enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (Section 17.2).
  5. Single-dimensional arrays of the above types. source

Source: stackoverflow.

You CAN DECLARE passing an array of a custom type:

class TestType
{
  public int Id { get; set; }
  public string Value { get; set; }

  public TestType(int id, string value)
  {
    Id = id;
    Value = value;
  }
}

class TestAttribute : Attribute
{
  public TestAttribute(params TestType[] array)
  {
    //
  }
}

but compilation errors occur on the attribute declaration:

[Test(new[]{new TestType(1, "1"), new TestType(2, "2"), })]
public void Test()
{

}
like image 140
vladimir Avatar answered Sep 24 '22 12:09

vladimir