views:

158

answers:

2

This is the Pascal sample I want to achieve in C#:

With myBook do
 Begin
  Title  := 'Some Book';
  Author := 'Victor John Saliba';
  ISBN   := '0-12-345678-9';
  Price  := 25.5;
 End;
+7  A: 

Only when constructing.

var foo = new Foo
{
  Title = "lol",
  Author = "Som Gai",
  ISBWhatever = "111"
}

VB.NET has the 'with' keyword, but c# does not.

Will
Note that this is only available in C# 3.0 and later.
Drew Noakes
Thanks, but I don't want to make new object.
ni5ni6
There is no equivalent. You can only do this kind of thing when initializing a new object.
Will
+6  A: 

Here you can find an explanation here.

Excerpt:

  • Small or non-existent readability benefits. We thought the readability benefits were small or non-existent. I won't go as far as to say that the with statement makes code less readable, but some people probably would.
  • Increased language complexity. Adding a with statement would make the language more complex. For example, VB had to add new language syntax to address the potential ambiguity between a local variable (Text) and a property on the "with" target (.Text). Other ways of solving this problem also introduce language complexity. Another approach is to push a scope and make the property hide the local variable, but then there's no way to refer to the local without adding some escape syntax.
  • C++ heritage. C++ has never had a with statement, and the lack of such a statement is not generally thought to be a problem by C++ developers. Also, we didn't feel that other changes -- changes in the kind of code people are writing, changes in the platform, other changes in the language, etc. -- made with statements more necessary.
Misha N.