Quick FAQ: How to use “With…End With” VB statement in C#?
Q: With…End With VB (.NET) also statement is very handy time saver. It makes you able to initialize properties of the object within one statement. Is there equivalent for this “With…End With” statement in C#?
Dim myObj As New MyObj()
With myObj
.OneProperty = "Hello"
.AnotherProperty = 2008
.YetOtherProperty = "World"
End With
A: Yes it is. You should use following syntax to archive the same functionality.
MyObj myObj = new MyObj {
OneProperty = "Hello",
AnotherProperty = 2008,
YetOtherProperty = "World"
};
By the way. VB.NET (with Linq extension) also has similar syntax
Dim myObj = New MyObj() {
.OneProperty = "Hello"
.AnotherProperty = 2008
.YetOtherProperty = "World" }
In addition, it can be anonymous in both languages
VB.NET
Dim myObj = New With {
.OneProperty = "Hello"
.AnotherProperty = 2008
.YetOtherProperty = "World" }C#
var myObject = new {
OneProperty = "Hello",
AnotherProperty = 2008,
YetOtherProperty = "World"
};
Have a nice day.
March 26th, 2008 · Comments (2)
2 Responses to “Quick FAQ: How to use “With…End With” VB statement in C#?”
Leave a Reply
Discover other tags
My tools
- .NET Framework Detector
- Duplicate images finder
- Exchange Security Policy for Windows Mobile Devices Fix
- Gas Price Windows Vista SideBar gadget
- Israel Traffic Information Windows Vista SideBar gadget
- Localization fix for SAP ES Explorer for Visual Studio
- LocTester
- RTL and LTR in Windows Live Writer
- Silverlight controls library
- Snipping tool integration plugin for WLW
- USB FM receiver library
- Vista Battery Saver
- WebCam control for WPF
- Windows Live SkyDrive attachment for Windows Live Writer
- Wireless Migrator
- WPF Virtual Keyboard





January 1st, 2009 at 12:43 am
That’s hardly an equivalent structure. Your C# example only works if used as a part of object instantiation. With…End With works on an object any time during its lifetime.
January 1st, 2009 at 12:43 am
Small comment on this: it will work ONLY in C# v3 (i.e. Visual Studio 2008) and up.
This syntax will not compile in C# v2 (i.e. Visual Studio 2005). Following error will be received: "A new expression requires () or [] after type"
Enjoy,
Alex