Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the C# equivalent to the With statement in VB? [duplicate]

Tags:

c#

vb.net

Possible Duplicate:
Equivalence of “With…End With” in c#?

There was one feature of VB that I really like...the With statement. Does C# have any equivalent to it? I know you can use using to not have to type a namespace, but it is limited to just that. In VB you could do this:

With Stuff.Elements.Foo
    .Name = "Bob Dylan"
    .Age = 68
    .Location = "On Tour"
    .IsCool = True
End With

The same code in C# would be:

Stuff.Elements.Foo.Name = "Bob Dylan";
Stuff.Elements.Foo.Age = 68;
Stuff.Elements.Foo.Location = "On Tour";
Stuff.Elements.Foo.IsCool = true;
like image 850
Bob Dylan Avatar asked Jul 24 '09 01:07

Bob Dylan


People also ask

What is meant by C?

noun plural c's, C's or Cs. the third letter and second consonant of the modern English alphabet. a speech sound represented by this letter, in English usually either a voiceless alveolar fricative, as in cigar, or a voiceless velar stop, as in case.

What is C for computer?

C is a powerful general-purpose programming language. It can be used to develop software like operating systems, databases, compilers, and so on. C programming is an excellent language to learn to program for beginners.

What is C in simple language?

C is a general-purpose high level language that was originally developed by Dennis Ritchie for the Unix operating system. It was first implemented on the Digital Eqquipment Corporation PDP-11 computer in 1972. The Unix operating system and virtually all Unix applications are written in the C language.

What is C and why it is used?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


3 Answers

Not really, you have to assign a variable. So

    var bar = Stuff.Elements.Foo;     bar.Name = "Bob Dylan";     bar.Age = 68;     bar.Location = "On Tour";     bar.IsCool = True; 

Or in C# 3.0 and above:

    var bar = new FooType     {         Name = "Bob Dylan",         Age = 68,         Location = "On Tour",         IsCool = True     };      Stuff.Elements.Foo = bar; 
like image 86
Robert Harvey Avatar answered Sep 23 '22 14:09

Robert Harvey


Aside from object initializers (usable only in constructor calls), the best you can get is:

var it = Stuff.Elements.Foo; it.Name = "Bob Dylan"; it.Age = 68; ... 
like image 30
Pavel Minaev Avatar answered Sep 24 '22 14:09

Pavel Minaev


The closest thing in C# 3.0, is that you can use a constructor to initialize properties:

Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}
like image 26
foson Avatar answered Sep 24 '22 14:09

foson