Well the title is partially true. But first a quick recap of what is object initializer and why I love them.

Recap

In C# 3.0 (will ship with next version of Visual Studio) if you have public properties/fields in a class as follows, then you can directly assign values to them while creating instance of the class.

class Customer

{

public string name;

public string address;

int age;

public int Age { get { return age; }
set { age = value; } }

}
var cust = new Customer{name = "Abhinaba Basu",
address =
"1835 73rd Ave NE",
Age = 99 };

So no need of creating the object first and using a statement each for each of the assignments. Read further about this and the syntactic sugar behind this here.

Custom Attributes and object initialization

Custom attributes supported something like this all along. It worked for public properties and fields, but worked only for custom attributes and not for all classes. Consider the custom attribute definition

[AttributeUsage(AttributeTargets.All)]
public class DescriptionAttribute: Attribute
{
public DescriptionAttribute(string description)
{
this.description = description;
detailedDescription =
string.Empty;
}
public string Description
{
get { return description; }
}
public string Detailed
{
get { return detailedDescription;}
set { detailedDescription = value; }
}
private string description, detailedDescription;
}

[Description("Nice class", Detailed = "Detailed descr")]

class MyClass

{

}

If you notice carefully this is special syntax and when the atrribute is being applied to MyClass we are using property=value inside the attribute initialization code. This syntax is similar to object initializer. Here Detailed is called the optional argument for the attribute.

You can get to the custom attribute using something like

MyClass mc = new MyClass();
object[] attrs = mc.GetType().GetCustomAttributes(true);
if (attrs != null && attrs.Length > 0)
{
DescriptionAttribute descr = (DescriptionAttribute)attrs[0];
Console.WriteLine(descr.Description);
Console.WriteLine(descr.Detailed);
}