views:

233

answers:

3

I have an object with a number of properties.

I want to be able to assign some of these properties when I call the constructor.

The obvious solution is to either have a constructor that takes a parameter for each of the properties, but that's nasty when there are lots. Another solution would be to create overloads that each take a subset of property values, but I could end up with dozens of overloads.

So I thought, wouldn't it be nice if I could say..

MyObject x = new MyObject(o => o.Property1 = "ABC", o.PropertyN = xx, ...);

The problem is, I'm too dim to work out how to do it.

Do you know?

Any pointers will be gratefully received.

--
Stuart

+6  A: 

C# 3 allows you to do this with its object initializer syntax.

Here is an example:

using System;

class Program
{
    static void Main()
    {
     Foo foo = new Foo { Bar = "bar" };
    }
}

class Foo
{
    public String Bar { get; set; }
}

The way this works is that the compiler creates an instance of the class with compiler-generated name (like <>g__initLocal0). Then the compiler takes each property that you initialize and sets the value of the property.

Basically the compiler translates the Main method above to something like this:

static void Main()
{
    // Create an instance of "Foo".
    Foo <>g__initLocal0 = new Foo();
    // Set the property.
    <>g__initLocal0.Bar = "bar";
    // Now create my "Foo" instance and set it
    // equal to the compiler's instance which 
    // has the property set.
    Foo foo = <>g__initLocal0;
}
Andrew Hare
Crikey. That was quick.Would you be offended if I asked for a <i>little</i> more detail? As I said, I am pretty dim.
Stuart Hemming
Didn't see your example when I first noticed your reply.
Stuart Hemming
A: 
class MyObject
{
     public MyObject(params Action<MyObject>[]inputs)
     {
          foreach(Action<MyObject> input in inputs)
          {
               input(this);
          }
     }
}

I may have the function generic style wrong, but I think this is sort of what you're describing.

Oliver N.
A: 

Basically what Andrew was trying to say is if you have a class (MyObject for eg) with N properties, using the Object Initializer syntax of C# 3.0, you can set any subset of the N properties as so:

MyObject x = new MyObject {Property1 = 5, Property4 = "test", PropertyN = 6.7};

You can set any of the properties / fields that way./

CODES_ONLY