Share via


C#: Object initializers were there in 1.0 as well

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; }
    }
    publicstring 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);
}

Comments

  • Anonymous
    April 19, 2006
    The comment has been removed
  • Anonymous
    April 19, 2006
    Ah, forget my question, saw your answer at http://blogs.msdn.com/abhinaba/archive/2005/09/17/470358.aspx#470835
  • Anonymous
    April 19, 2006
    one more interesting coding practice is the use of base key word while calling base constructor

    eg:

    class HostedModule
    {
      private _Module;
      public HostedModule(string Module)
      {
        _Module=Module;
      }
    }

    class HostedApp : HostedModule
    {
     public _moduleName="Module Name";
     public HostedApp(string App) : base(_moduleName)
     {
       
     }
    }