2

Given object initializers:

Foo foo = new Foo{ Name = "Jhon", Value = 2, IsMale = true };

Can they be somehow used elsewhere?(outside object construction) So that insted of using:

foo.Name = "Name";
foo.Value = 5;
...
foo.DoSth();

To just use something like:

Name = "Name";
Value = 5;
...
DoSth();

Given that this is outside the class hierarchy of foo. That is to avoid places where you use one object's members many many times.

For example in VB/GML(GameMaker's scripting language) one can use:

with(foo)
{
    Name = "Name";
    Value = 5;
    ...
    DoSth();
}

Instead of foo.something

So is there something like this in C#?

Bosak
  • 2,103
  • 4
  • 24
  • 43
  • 1
    Why not to have a `parameterized` constructor on `Foo` instead? – Rohit Vats Jun 01 '13 at 17:33
  • @I4V oh I didn't knew VB had this thing too. Thanks for noteing. – Bosak Jun 01 '13 at 17:34
  • @RohitVats that is not what I asked for. My question isn't about using constructors or object initializers. It is where you already have a built object and instead of typeing a lot of foo.something to use objectinitializer-like syntax, but I now know that it is not possible in C#. – Bosak Jun 02 '13 at 16:31

1 Answers1

1

No, object initializer is the only place where assignment syntax like that can be used. If you need to assign multiple fields at once from many different places in code without duplication, you could define a method that encapsulates all the assignments for you:

void SetNameAndGender(string f, string l, bool isMale) {
    FirstName = f;
    LastName = l;
    IsMale = isMale;
}

Unfortunately, it does not let you set an arbitrary group of properties, like the VB syntax that you show.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523