1

Is a way to set the properties of an object in a block using C#, similar to how you write an object initializer?

For example:

Button x = new Button(){
    Text = "Button",
    BackColor = Color.White
};

Is there a syntax similar to this that can be properties after the object has been created?

For example:

Button x = new Button();
x{
   Text = "Button",
   BackColor = Color.White
};
Brian
  • 7,955
  • 16
  • 66
  • 107
Furkan
  • 415
  • 5
  • 17
  • Possible duplicate of [With block equivalent in C#?](http://stackoverflow.com/questions/481725/with-block-equivalent-in-c) – sstan Dec 04 '15 at 23:10
  • This is called an [object initializer](https://msdn.microsoft.com/en-us/library/bb384062.aspx) and can only be used when `new`ing an object. Your second piece of code is simply not valid C#. – Pieter Witvoet Dec 04 '15 at 23:27
  • Thanks - Pieter Witvoet.You gave me the answer I want – Furkan Dec 04 '15 at 23:48

4 Answers4

1

You can do it like this; say you have a class named Platypus.

Your grandfather's way:

Platypus p = new Platypus();
p.CWeek = "1";
p.CompanyName = "Pies from Pablo";
p.PADescription = "Pennsylvania is the Keystone state (think cops)";

The newfangled way:

Platypus p = new Platypus
{
    CWeek = "1",
    CompanyName = "Pies from Pablo",
    PADescription = "Pennsylvania is the Keystone state (think cops)"
};
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 1
    this has to be the most random example code I have seen. Way to be creative – BenCamps Dec 05 '15 at 00:31
  • This doesn't answer the question at all. He's asking for a special syntax for setting properties ***after*** the object is already created. – sstan Dec 05 '15 at 00:31
  • The one who understands best what I want to tell -sstan, thanks. I got my answer. There is no indication in the way I want. – Furkan Dec 05 '15 at 10:52
0

May be you want it?

Button x = new Button();
x.Text = "Button";
x.BackColor = Color.White;
Denis Bubnov
  • 2,619
  • 5
  • 30
  • 54
0

You can do this with property initializers.

Button x = new Button { Text = "Button", BackColor = Color.White };
wentimo
  • 471
  • 3
  • 12
  • 1
    This is identical to the first listing in the question. OP's asking for the ability to do this on the instance itself once it has been created. – Brian Rasmussen Dec 05 '15 at 00:30
0

This form

Button x = new Button(){
    Text = "Button",
    BackColor = Color.White
};

Is part of the syntax for constructors and constructors only. You can't use the same syntax on the next line. You can leave out the (), though, and use a var for the variable type, to give you the more compact;

var x = new Button{
    Text = "Button",
    BackColor = Color.White
};

After construction, the only way to update it is through normal assignment operations;

x.Text = "Button";
Steve Cooper
  • 20,542
  • 15
  • 71
  • 88