1

Is there a way to set multiple properties with one declaration in Windows Forms C#?

I'm making a skill calculator for a game and I would like be able to do something like this:

someControl.Text = "some text",
           .BackgroundImage = "someImage.jpg";

Is it possible to do something like that?

kylieCatt
  • 10,672
  • 5
  • 43
  • 51
  • 2
    [Why doesn't C# have VB.NET's 'with' operator?](http://blogs.msdn.com/b/csharpfaq/archive/2004/03/11/why-doesn-t-c-have-vb-net-s-with-operator.aspx) – David Heffernan Jun 10 '13 at 20:59
  • 1
    Because it's really not necessary, just do a `var x=someControl;` then you can `x.Text=...` and `x.BackgroundImage=...` all you want. If you don't like that, and you are setting a lot of properties, then when you are done, hold down the alt and highlight all the `x`s, and type someControl, then delete the `var x=someControl;` if you just wanted to save typing. – Robert McKee Jun 10 '13 at 21:04
  • I used to wonder, too. But seeing that these blocks can be nested and span several hundreds of lines, I think the brains behind C# took the right decision. For readability and clarity. – Mathieu Guindon Jun 10 '13 at 21:06

3 Answers3

7

In VB, you could use the "WITH" keyword. The closest thing in C# is the constructor that takes an object initializer.

var someControl = new Control() {
                         Text = "SomeText",
                         BackgroundImage "someImage.jpg" };

but no, I don't think there is a way to do what you are asking in C#.

Bill Gregg
  • 7,067
  • 2
  • 22
  • 39
2

What you're talking about is a fluent interface[Wikipedia]. Unfortunately, there is not a way to chain properties in a fluent way in C#. A type initializer block could be used to achieve almost the same effect, but only when you're constructing the object. Because it's WinForms, the constructing is probably happening in the designer generated code. Best not to monkey with that.

You can, however, create a fluent interface using methods, if you desire:

class Widget
{
    public Widget SetFoo(int foo)
    {
        // Set the Foo property or whatever...
        return this;
    }

    public Widget SetBar(int bar)
    {
        // Set the Bar property or whatever...
        return this;
    }
}

Then, you can use the class like so:

var w = new Widget().SetFoo(23).SetBar(42);

You can even do this for .NET framework types and controls using extension methods. However, unless you're using it a lot, adding such an interface to a framework class is probably overkill.

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
1

If you are creating (or rather, constructing) SomeControl, you can use an initializer;

myControl = new SomeControl {
    Text = "blablabla",
    BackgroundImage = "someimage.jpg" };

Otherwise your answer is a plain a boring "no"...

Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235