DCSIMG
Quick FAQ: How to use “With…End With” VB statement in C#? - Just code - Tamir Khason
Thursday, March 27, 2008 10:19 AM Tamir Khason

Quick FAQ: How to use “With…End With” VB statement in C#?

[This blog was migrated. You will not be able to comment here.
The new URL of this post is http://khason.net/blog/quick-faq-how-to-use-%e2%80%9cwith%e2%80%a6end-with%e2%80%9d-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.

תגים:, , ,

Comments

No Comments