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]
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.
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.
If you really miss it, you can create a local variable with a single character name. At that stage you only have to type one more character per line – is that really a hardship?
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?
local variable with single character name? If the argument is for readability, this doesn’t seem to fit
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.
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.
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.
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.
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!
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;
}
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.
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.
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
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)
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.
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.
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.
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";
}
}
}
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.
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.
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.
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 🙂
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.
To all you "real programmers" out there who program in "real languages" – stick it in your ear.
Your high level of arrogance is only matched by your low levels of social grace. I’ll bet you got beat up on the playground, too.
The With statement is a fine language construct, and is no more superfluous than "var" or "using" or that stupid curly bracket. If you don’t like it, you don’t have to use it, but saying it is bad because you don’t like it is a really stupid argument.
The original question was "why doesn’t c# have a ‘with’ statement," not "How many ‘real programmers’ out there dislike the ‘with’ statement?"
Someone brought up a good point about nested properties or types:
Foo.Something.Type.TextColor = red;
Foo.Something.Type.StrokeColor = black;
Foo.Something.Type.StrokeWidth = 2;
Foo.Something.Type.BackgroundColor= Blue;
I would like a 'With' statement. syntax similar
With(Foo.Something.Type)
{
.TextColor = red;
.StrokeColor = black;
.StrokeWidth = 2;
BackgroundColor = Blue;
}
now, get your hate on for me wanting a 'with' statement. I don't care, I've seen this implementation need over and over.
I fully agree with Chris. a with keryboard and curly braces is ideal.
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.
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?
I totally agree that "With" is needed. I so support the implementation idea from Chris:
Chris 16 Jun 2010 12:57 AM
With(Foo.Something.Type)
{
.TextColor = red;
.StrokeColor = black;
.StrokeWidth = 2;
.BackgroundColor = Blue;
}
I run into this in a million places where different properties
have to changed. And, it is simple to do it in this manner.
Also, it provides code re-use. You grab and copy the code,
then jump elsewhere and reuse it by just changing the reference
in the With.
Yet, I want to comment on Krishan Ariyawansa's post (22 Nov 2009 9:02 PM)
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.
Yet, K.A., this only works when you are creating the object initially.
it will not work later on after the object is instantiated.
So, I hope the C# designers listen and add this simple bit of code to
assist developers who have this need alot.
And, I counter and disagree that inheritance will not always solve this
issue. I agree inheritance should be used when possible, but not every
single situation can be solved in the best manner by an already existing
methodology.
Thanks for listening,
David Blaine Fullerton
You can't have it cuz some don't like it, is BS. arn't we adults here? Can't I CHOOSE to write MY code the way I like to read it? No one at M$ will EVER read MY code….
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?
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.
Thread hasn't been very busy lately, but I'd like to throw in my vote for adding the With syntax as defined by Chris above to the C# language. I don't believe it was stated there, but I'm also assuming his syntax would allow for nested With's.
The readability argument against With is too subjective, with people falling on both sides. Personally, I find the syntax to be concise and very readable.
And there's the added benefit of being able to cut-and-paste similar With blocks into your code and only needing to change the reference on the With line to work with different objects.
I'd also like to know the answer that DavidJ asked about; I too was taught that With in VB would save multiple COM object de-referenceing, which was thought to be a good thing. I still want With as a language option in C# regardless, but would like to know if With would provide similar benefits here as well. If it does, that shoots in the foot the idea of creating an abbreviated local variable to provide "the same functionality as With" – creating a new variable would negate the multiple reference benefit.
Given that the language team has already provided Using in C#, I can't see any valid reason for them to not give us With when so many people clearly want it – and for those that don't, simply don't use it.
Unless there is truly some horrible thing behind the scenes that With might be guilty of that isn't also true of Using… ? Someone ? Anyone ?
TFL…
@Wardy…
"My advice, learn your language and learn it well, don't complaing about it."
Good work following your own advice.
yes, i'd like with as well.
It's painful enough using c# in the first place – with might make in marginally easier.
i need euivalent function of With End With in c#.
Can u plz help me.
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.
And then C# created the OBJECT INITALIZATER FEATURE
this is ridiculous, WITH is a huge plus for code readability
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??
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.
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 !
"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!