28

I was looking at the online help for the Infragistics control library today and saw some VB code that used the With keyword to set multiple properties on a tab control. It's been nearly 10 years since I've done any VB programming, and I had all but forgotten that this keyword even existed. Since I'm still relatively new to C#, I quickly went to see if it had a similar construct. Sadly, I haven't been able to find anything.

Does C# have a keyword or similar construct to mimic the functionality provided by the With keyword in VB? If not, is there a technical reason why C# does not have this?

EDIT: I searched for an existing entry on this before asking my question, but didn't find the one Ray referred to (here). To refine the question, then, is there a technical reason why C# does not have this? And Gulzar nailed it - no, there are not a technical reason why C# does not have a With keyword. It was a design decision by the language designers.

Community
  • 1
  • 1
Matt Davis
  • 45,297
  • 16
  • 93
  • 124
  • (off topic; you asked about protobuf-net - drop me an e-mail at marc.gravell@gmail.com) – Marc Gravell Mar 27 '09 at 12:44
  • In addition to what Gulzar Nazim stated, I was at a conference where this question was asked of Anders Helsburg. His answer was more... succinct. 'C# will never provide support for the With keyword' – SASS_Shooter May 15 '13 at 19:49

7 Answers7

26

This is what C# program manager has to say: Why doesn't C# have a 'with' statement?

  • Small or non-existent readability benefits. We thought the readability benefits were small or non-existent. I won't go as far as to say that the with statement makes code less readable, but some people probably would.

  • Increased language complexity. Adding a with statement would make the language more complex. For example, VB had to add new language syntax to address the potential ambiguity between a local variable (Text) and a property on the "with" target (.Text). Other ways of solving this problem also introduce language complexity. Another approach is to push a scope and make the property hide the local variable, but then there's no way to refer to the local without adding some escape syntax.

  • C++ heritage. C++ has never had a with statement, and the lack of such a statement is not generally thought to be a problem by C++ developers. Also, we didn't feel that other changes -- changes in the kind of code people are writing, changes in the platform, other changes in the language, etc. -- made with statements more necessary.

Community
  • 1
  • 1
Gulzar Nazim
  • 51,744
  • 26
  • 128
  • 170
  • 1
    @Gulzar - Thanks for the link. It 'scratched the itch,' although I disagree with Mr. Wiltamuth's first two lines of reasoning. The with keyword, for me, has less to do with readability than it does about making the code easier to write... – Matt Davis Mar 02 '09 at 03:35
  • 2
    ... And I find it difficult to believe that a with keyword is anywhere near the complexity involved with LINQ, anonymous methods, etc., but I digress. Thanks again for the link. – Matt Davis Mar 02 '09 at 03:36
  • You are right on the money, but the explanation is weak. C++ heritage didn't include a whole bunch of stuff that is in the modern data C#. – AngryHacker Mar 02 '09 at 05:08
  • These are explanations of **C# program manager**. Any VB.NET developer knows how much _With_ keyword improves code quality: no temporary variables, quick casting, much less code to reach same goals when compared to C#. – Dima May 02 '16 at 20:50
16

In C# 3.0, you can use object initializers to achieve a similar effect when creating objects.

var control = new MyControl
{
    Title = "title",
    SomeEvent += handler,
    SomeProperty = foo,
    Another = bar
};

Rather than:

var control = new MyControl();
control.Title = "title";
control.SomeEvent += handler;
control.SomeProperty = foo;
control.Another = bar;

Note that, although this syntax was introduced in C# 3.0, you can still use it with the 2.0 framework, it's just syntactic sugar introduced by the compiler.

Matthew Olenik
  • 3,577
  • 1
  • 28
  • 31
11

It is not idiomatic c#, but if you really want a with equivalent, you could do this:

Person MyPersonWithALongName = new Person();
MyUtils.With(MyPersonWithALongName, p => {

    p.Name = "George";
    p.Address = "123 Main St";
    ...

});

class MyUtils {

    public static void With<T>(T x, Action<T> do) {
        do(x);
    }
}

Update:
It occurred to me that you could trivially make this more concise by turning it into an extension method, perhaps renaming it "Alias" or "As" for reabability:

MyPersonWithALongName.Alias(p => {
    p.Name = "George";
    p.Address = "123 Main St";
    ...
});
Gabe Moothart
  • 31,211
  • 14
  • 77
  • 99
  • 8
    you'd want to make sure to restrict T to be a reference type ("where T : class"), so that you don't accidentally edit a copy of struct x – lightw8 Jan 18 '12 at 19:19
9

No, the "with" keyword was intentionally left out of the language.

If you have a lengthy name of reference, you can easily make a shorter reference to it using a variable, and even give it a limited scope:

{
   SomeClass r = Some.Lengthy.Path.To.Get.To.A.Referece;
   r.Some = 42;
   r.Properites = "none";
   r.To = 1;
   r.Set = null;
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

For these solutions:

// ....
// (class Common)

public static void With<T>(T property, Action<T> action) {
    action(property);
}

// ...
// usage somewhere ...    
Person person = GetPerson();
Common.With(person, p => { p.Name = "test", p.Age = "123" });

It just seems we are aliasing the variable with "p". As solutions go, I found it easy enough to keep the variable name short, this sort of solution with a "With" generic doesn't buy any elegance.

Ideally, we'd all like to see some reworking of the syntax so the usage is similar to how initialization of multiple properties works today:

Person person = new Person() { Name = "test", Age = "123" };
sonjz
  • 4,870
  • 3
  • 42
  • 60
0

No, it was a conscious decision made by the C# dev team. People have mixed feelings about the 'with' keyword because it can degrade code readability if abused (nesting with's).

Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • I wasn't aware you could nest "with" statements. That would reduce readability. However, like the GoTo and many other programming constructs, if used well, is it really all that bad? – Kibbee Mar 02 '09 at 03:14
  • 1
    I think it can be nice if used properly. – Ed S. Mar 02 '09 at 03:43
-1

I don't imagine that there's a technical reason it doesn't exist. What I would say though, is that the reason that it doesn't exist is that it's a programming construct that exists solely for the purpose of cutting down on typing. With things like intellisense, and copy and paste, the world doesn't really have much demand for features like this anymore. I use VB.Net, and can't recall if it's even still supported. Never really felt the need to use it.

Kibbee
  • 65,369
  • 27
  • 142
  • 182