What is the equivalent syntax in C #, if any?

Does C # have an equivalent for VB6

With End With 
+7
syntax c # vb6 equivalent
source share
8 answers

There is nothing equivalent, but C # 3 got the opportunity to set properties when building:

 var person = new Person { Name = "Jon", Age = 34 }; 

And collections:

 var people = new List<Person> { new Person { Name = "Jon" }, new Person { Name = "Holly"} }; 

This is definitely not a replacement for all uses With , but it is worth knowing for some of them.

+19
source share

C # does not have equivalent syntax. The closest are the object initializers, but they do not match:

 var obj = new SomeThing { Height = 100, Text = "Hello, World", ForeColor = System.Drawing.Color.Green } 
+14
source share

Not.

What is suitable is an object and a list of initializers .

 Person p = new Person() { FirstName = "John", LastName = "Doe", Address = new Address() { Street = "1234 St.", City = "Seattle" } }; 
+6
source share

This is by no means the equivalent, however, if it is a typing that you are trying to reduce, you can do it.

 { var o = myReallyReallyReallyReallyLongObjectName; o.Property1 = 1; o.Property2 = 2; o.Property3 = 3; } 
+4
source share

There is no C # equivalent for the Visual Basic With keyword.

+2
source share

There is no equivalent in C # → more details here in the comments http://blogs.msdn.com/b/csharpfaq/archive/2004/03/11/why-doesn-tc-have-vb-net-s-with- operator.aspx

+2
source share

One almost equivalent call invokes a method that is a member of the class. You do not need to repeatedly name the owner object inside the members of the class - this is implied in the fact that the function is a member called for this instance.

I doubt the direct equivalent of With / End With is a good idea in C # for this reason. If you find that you repeatedly entered the name of an object in a given area, this is a good sign that the code in question will make a good method for this class of objects.

+1
source share

There is no direct equivalent. You can set properties when building, as others have explained, or you can assign your expression to a variable with a short name. The following should be semantically equivalent:

 With <expression> .something ... .somethingElse ... End With var w = <expression>; w.something ... w.somethingElse ... 
+1
source share

All Articles