Share via


Why doesn't C# have VB.NET's 'with' operator?

Many people, including the C# language designers, believe that 'with' often harms readability, and is more of a curse than a blessing. It is clearer to declare a local variable with a meaningful name, and use that variable to perform multiple operations on a single object, than it is to have a block with a sort of implicit context.

For more information, see the Ask a C# Language Designer page.

[Author: Jon Skeet]

Comments

  • Anonymous
    March 10, 2004
    We will have namespace aliases which I think is BAD, that coupled with lambda functions. C# is becoming Turd# whats next, partial methods? Dont even go there.

  • Anonymous
    March 10, 2004
    Not having with in C# is about the only thing that I miss from VB. If you think with caues that much confusion then what about using? Shouldn't we really be spelling out the enitire namespace evertytime we use a type?
    Of course with can be abused(like everything else) but if used right then it is a quite nice construct to save repetitive typing IMHO.




  • Anonymous
    March 10, 2004
    The comment has been removed

  • Anonymous
    March 10, 2004
    I'm with Christoffer: when I program C#, I want the With statement. When scoped properly, I find it very handy. Of course, it can be abused, such as when you have nested With statements. That being said, if each language had the same features, would we need different languages?

  • Anonymous
    March 10, 2004
    local variable with single character name? If the argument is for readability, this doesn't seem to fit

  • Anonymous
    March 11, 2004
    Jon,

    Doesn't creating a short variable name cause code readability problems and isn't that the problem the C# team is trying to avoid with not including the With statement?

    Personally, I find code that uses the With statement very readable.

  • Anonymous
    March 11, 2004
    Yes, it does. However, if someone wants with and the lack of readability it gives, presumably that isn't an issue for them. My point is that the lack of this "feature" really can't hurt very much for those who want it.

  • Anonymous
    March 11, 2004
    If I had to single out one thing I miss in C# (I'm coming from Delphi) - it would surely be the lack of 'with' statement.

    Mind you, having support for multiple structures in 'with' statement, like 'with A,B do' is abomination.

  • Anonymous
    March 11, 2004
    Delphi (i.e. Pascal) with statement has one very bad side effect. It is possible to alter meaning of a unit by adding a field to a structure in another unit. New fied can overlap local variables. This is not easy to track, because source control says that file was not changed recently.

  • Anonymous
    March 24, 2004
    Being a paying customer and not, admittedly, a purist who thinks he knows how everyone else should code, I'd like to see the With operator in a future release of C#.

    Just don't force the people who fuss over whether a black sweater goes better with their khakis than a dark blue one to use it, whatever you do!

  • Anonymous
    April 14, 2004
    The closest C# equivalent to VB's With statement is illustrated in the following example:

    using (DataGrid x = DataGridList)
    {
    x.GridLines = GridLines.Both;
    x.BackColor = System.Drawing.Color.White;
    x.BorderStyle = BorderStyle.None;
    x.ShowFooter = false;
    x.ShowHeader = true;
    x.AllowPaging = true;
    x.AllowCustomPaging = true;
    x.AllowSorting = true;
    x.CellPadding = 4;
    }

  • Anonymous
    May 18, 2004
    Jon, it'd be better for the debate if you stopped saying that 'with' gives a lack of readability. Clearly people's opinions vary on this one.

  • Anonymous
    May 25, 2004
    However Using(x) only works if x implements the IDispose interface.

    From a language "flavor" point of view (which is admittedly very subjective) it sort of feels right to me that VB, which tries to make your life easier at the expense of absolute purity of the language (see RaiseEvent for an example), would support With while C# does not. It's a bit odd that the result is that in this case VB code can be more terse than C#. I actually find it stranger that C# has the using() statement, which seems to be more in keeping with VB's philosophy.

  • Anonymous
    June 02, 2004
    WITH is horrible. It's only a problem for people that haven't programmed in a real language before; VB would be better off for those people anyhow. Think about it VB lovers, WITH "saves so much space", but you also use THEN and END IF as opposed to { and }. THEN and END IF appear MUCH more often than WITH ever should. If you rely on mechanisms like WITH, then you should seriously reconsider how you design your software, if you do at all. If I had to complain about C# lacking features, I would be asking where C-style Unions are. Splitting packets manually rather than by a union of an array and a struct is a pain

  • Anonymous
    June 11, 2004
    Uh... respect?
    As you can see here, there are quite a few people who like 'with', and Mr Clifton, you just disrespected ALL of them - so anyone who likes 'with' is a terrible programmer, and anyone who programs in VB is not a 'real' programmer? This sounds like a post that belongs on a Linux board (in keeping with Mr Clifton's blanket statements)

  • Anonymous
    July 04, 2004
    I must agree with 'invid': Mr. Clifton is coming across a little on the arrogant side. I can see both sides of this issue, and I think we should appreciate the subjectiveness of it, without resorting to degrading the validity of others' programming ability.

  • Anonymous
    July 22, 2004
    With is a code smell, learn better way's to program, for example... Rather than working with built in types... inherit from them so you can improve the API, consider the following previous example

    using (DataGrid x = DataGridList)
    {
    x.GridLines = GridLines.Both;
    x.BackColor = System.Drawing.Color.White;
    x.BorderStyle = BorderStyle.None;
    x.ShowFooter = false;
    x.ShowHeader = true;
    x.AllowPaging = true;
    x.AllowCustomPaging = true;
    x.AllowSorting = true;
    x.CellPadding = 4;
    }

    rather than doing that... consider an argument accumulator pattern which allows named arguments in any order with all being optional.

    aDataGridList
    .GridLines(GridLines.Both)
    .BackColor(System.Drawing.Color.White)
    .CellPadding(4);

    aDataGridList
    .AllowPaging(true)
    .AllowCustomPaging(true)
    .AllowSorting(true)
    .CellPadding(4);

    aDataGridList
    .GridLines(GridLines.Both)
    .BackColor(System.Drawing.Color.White)
    .BorderStyle(BorderStyle.None)
    .ShowFooter(false)
    .ShowHeader(true)
    .AllowPaging(true)
    .AllowCustomPaging(true)
    .AllowSorting(true)
    .CellPadding(4);

    Basically, whenever you find yourself needing to call the same object a bunch of times in a row... consider extending that object and providing either a single method to do that, or expose all props in an accumulator, either way... code that calls an object over and over and over... belongs in that object in the first place. No object should require you to set a bunch of properties constantly, that's why we have inheritance.

  • Anonymous
    July 23, 2004
    It shouldn't be too difficult to create a code generator that uses reflections to automatically generate an accumulator wrapper for any class... every property that reflections finds simply generates a method like so...

    class DataGridWrapper:DataGrid{
    public DataGridWrapper SetShowFooter(bool showFooter){
    ShowFooter=showFooter;
    return this;
    }
    }

    accumulators drastically improve the API of any object and are easily machine generated.

  • Anonymous
    July 23, 2004
    Here's a class to generate an accumulator decorator for any type... use like

    Response.Write(new ArgWrapperGenerator(typeof(DataGrid)).Generate()); //writes an argument acumulator decorator class for the datagrid..

    now you can do this...
    new DataGridAccumulator(aGrid)
    .SetThis(bla)
    .SetThat(bla)
    .SetSomethingElse(bla);

    no with statement necessary....

    code below..
    --------------------------------

    using System;
    using System.Reflection;
    using System.Collections;

    namespace AccumulatorDecorator {
    public class ArgWrapperGenerator {
    Type theGeneratedFor;

    public ArgWrapperGenerator(Type generateFor) {
    theGeneratedFor=generateFor;
    }
    public string Generate() {
    string result="";

    Hashtable nameSpaces = new Hashtable();
    foreach(PropertyInfo aProp in theGeneratedFor.GetProperties())
    if(aProp.CanWrite)
    nameSpaces[aProp.PropertyType.Namespace]=aProp.PropertyType.Namespace;

    foreach(DictionaryEntry aNamespace in nameSpaces)
    result+="using "+aNamespace.Value+";n";

    result+="public class "+theGeneratedFor.Name+"Accumulator{n";
    result+="tt"+theGeneratedFor.Name+" the"+theGeneratedFor.Name+";nn";
    result+="ttpublic "+theGeneratedFor.Name+"Accumulator("+theGeneratedFor.Name+" a"+theGeneratedFor.Name+"){n";
    result+="tttthe"+theGeneratedFor.Name+"=a"+theGeneratedFor.Name+";n";
    result+="tt}n";

    foreach(PropertyInfo aProp in theGeneratedFor.GetProperties())
    if(aProp.CanWrite)
    result+=GetProp(aProp);

    result+="t}n";

    return result;
    }
    string GetProp(PropertyInfo aProp){
    string result="ttpublic "+theGeneratedFor.Name+"Accumulator Set"+aProp.Name+"("+aProp.PropertyType.Name+" a"+aProp.Name+"){n";
    result+="tttthe"+theGeneratedFor.Name+"."+aProp.Name+"=a"+aProp.Name+";n";
    result+="tttreturn this;n";
    return result+"tt}n";
    }
    }
    }

  • Anonymous
    October 22, 2009
    Personally, I never used the with statement much in my vb days. But it had it's uses. Now that I'm using C#, and have to type Properties.Settings.Default.[variable] every time I want to access a property, the with statement would come in extremely handy, as Properties.Settings.Default doesn't implement IDisposable, and creating a variable to hold Properties.Settings.Default is still pretty much pointless, because in my case, I'm using this property very much like a local variable, where I don't want to type Properties.Settings.Default every time I need to access it, because I need to do this a lot, and thus this will take a lot of added time, that doesn't need to be taken.

  • Anonymous
    November 18, 2009
    I find with statement in VB.NET extremely annoying (apart from subjective readability issue where I reckon it is reducing the readability) when debugging in VS 2005. It is very slow and manual process to 'Add Watch' where inside a "with" block - or expecting a tool tip to pop up showing the current value of a variable but doesn't work in VS2005. Although I am a C# person I have to use VB.NET frequently, and this is one of those things that bugs me all the time.

  • Anonymous
    November 22, 2009
    It is possible with C#. Compiler will not reject the following code block.                Table table = new Table                {                    CellPadding = 0,                    CellSpacing = 0,                    BorderWidth = 0,                }; Cheers, Happy code-ing.

  • Anonymous
    December 13, 2009
    LOLZ ... All this over the word "WITH" haha ... I started out on VB then moved to .NET, I have to admit I see VB as a "training language" most people I know even those that work with it tell me this causes a lot of confusion about how to professionally use VB. My advice, learn your language and learn it well, don't complaing about it. I came a across a similar issue with optional parameters the other day, had to use reflection instead. Bit of a ball ache but it was my choice to live in fluffy C# land ... Just out of curiosity ... what MSIL does this With keyword generate ? Technically I reckon it makes a mess of your pre jit code so why not steer clear of it :)

  • Anonymous
    April 01, 2010
    saying 'With' decreases readability in VB is like saying 'var' decreases readability in C#.  shorthand is shorthand; don't use it if you don't want to, but at least give me the option.

  • Anonymous
    April 22, 2010
    The comment has been removed

  • Anonymous
    June 15, 2010
    The comment has been removed

  • Anonymous
    August 25, 2010
    I fully agree with Chris.  a with keryboard and curly braces is ideal.

  • Anonymous
    October 20, 2010
    Right now, I have twenty of so dropdowns and I need to change them all to add DataTextField and DataValueField. If there were a With statement in C#, I could cut and paste .DataTextField, .DataValueField, .DataSource, .DataBind into all the dropdowns in a few seconds.  But no, I have to cut and paste, and then change the name of the dropdown for each one.  If I forget, or mess one up, I have a bug.  "With" is good.  Just give it to us, and if you don't like it, don't use it.

  • Anonymous
    October 24, 2010
    There are so many arguments for, and so many alternatives. Perhaps there's a definitive argument against the 'with'?  IMHO it seems nice on the surface, but whats really going on underneath? Will it out perform the alternatives?

  • Anonymous
    December 12, 2010
    The comment has been removed

  • Anonymous
    January 02, 2011
    The comment has been removed

  • Anonymous
    June 27, 2011
    Hmm, I see this is an old thread. Just converting to c# myself. Was wondering about things like COM calls. A long time ago I learned that if you do something like: ppt.documents(1).slides(2).shapes(2).textrange.text = "Good" ppt.documents(1).slides(2).shapes(3).textrange.text = "Grief" it caused a bizzional com accesses and was really slow and they recommended using a with statement instead.  I don't know if anyone is still commenting on this debate but wondered if that wasn't an issue anymore or if c# handled that differently?

  • Anonymous
    July 24, 2011
    I wrote a blog(blog.baltrinic.com/.../c-equivalent-for-visual-basic-with-statement) some time back on how to simulate a with statement in c# using extension methods and lambda expressions.

  • Anonymous
    October 26, 2011
    The comment has been removed

  • Anonymous
    November 13, 2011
    @Wardy... "My advice, learn your language and learn it well, don't complaing about it." Good work following your own advice.

  • Anonymous
    November 14, 2011
    yes, i'd like with as well. It's painful enough using c# in the first place - with might make in marginally easier.

  • Anonymous
    February 26, 2014
    i need euivalent function of With End With in c#. Can u plz help me.

  • Anonymous
    March 18, 2014
    I would like to recommend against people using the using keyword as if it was VB’s with keyword. using implies that, once the block is closed, the used object should no longer be used. If an object controlled by a using block is used after the using block closes, that may work in some situations but not all (ObjectDisposedException anyone?) and will likely confuse people about the meaning of using. For now, the closest thing C# has to offer is:    {        var x = MyArbitraryObject;        x.Property1 = 1;        x.Property2 = 2;        {            var y = x.Property3;            y.SubProperty1 = -1;            y.SubProperty2 = -2;            y.SubProperty3 = -3;        }    } What I want to know is: why then does C# have the special new instantiation list syntax? This is barely different from what the requested with keyword’s syntax would be. So, obviously, C#’s authors themselves wanted the with syntax in this situation (object instantiation) but leave programmers who use a factory-like pattern adrift. And this still doesn’t answer why the syntax is perfectly readable/acceptable when constructing an object but not when trying to update a bunch of its properties later. You can get close to recreating the constructor-style syntax with extension methods and reflection. This results in a syntax like MyArbitraryObject.Set(new { Property1 = 1, Property2 = 2, });. However, this misses out on compile-time type checking and, well, has all the problems of deferred/runtime binding (efficiency, magic string constants (the keys in the new{} block are magic string constants which don’t even look like strings—because we’re getting as close to with <expression> { Property1 = 1, Property2 = 2, }; based on the new <classname>() { Property1 = 1, Property2 = 2, }; syntax as we can)). So, C# compiler support would be really nice… and would make the language less inconsistent with itself, IMO.

  • Anonymous
    December 01, 2014
    And then C# created the OBJECT INITALIZATER FEATURE

  • Anonymous
    May 14, 2015
    this is ridiculous, WITH is a huge plus for code readability

  • Anonymous
    June 30, 2015
    What? Horrible? Lack of Readability?  Then I think you are TOO ******. All we want is something like this.. with (whatever) {     whateverSomething1 = something1;     whateverSomething2 = something2;     whateverSomething3 = something3; } what is so bad about that??

  • Anonymous
    July 16, 2015
    Roslyns syntax factory capabilities should it make a bliss to implement the feature by vsix. On the other hand it might be a challenge to synchronize it with debugger features like walking through stepwise and showing contents (for example adding the shortcut watch ".property"). This is already solved in VB. Code readability has obviously been a flimsy put-off, facing now features like putting text formatting properties into such: public string fprop(arg1,arg2) => $"Here are {arg1} and {arg2}."; This is handy but helps remarkable to make the code look like someone rolled an armadillo along the keyboard. This is not what I can tell about the with-statement. It has been quite comfortable for setting up dataset properties and contents like nothing else. Important to notice: "With” can be used for assignments in mixed directions and for methods: With (my) { i.am = .Name; i.have = .Property; .Home=i.live; .Capabilities.Add(i.can); i.say=.Text.get(); } Along with the choice of working with existing or objects disposed by GC, using() and create() don't ever reach.

  • Anonymous
    August 17, 2015
    i also would like to see 'with' in C#, but for all of you who have complained about how it would help with copy/paste, i have a simple solution: write a function that takes the object as its parameter !

  • Anonymous
    January 31, 2016
    "Many People,  including the C# language designers" are just wrong. And nearly ANY language structure can have the pitfalls and be a curse if implemented badly. Consider the abuses of the switch operator as one example. Doesn't mean that the construct should not exist in C#. It is far too useful when implemented judiciously. I find it impossible to believe that readability is the reason. Look at the C# language.  How can it be less readable than, say: string str = (val < 0 | val ==30) ? $"Wow, {name1} is a genius", $"I told you, {name2} is an idiot" (and this is a very basic C# expression). If it were implemented in the manner that it is done in VB.NET, it would avoid some of the (valid) criticisms of it's misuse in Delphi. AND it would finally remove one of the things that are badly missing in the C# language. Please(!) put a WITH operator into the C# language. For the people that hate it - don't use it!