regex
regex

Reputation: 3601

Initialize Object Properties in One Line of Code

Question:

Hello All,

Sorry that this is kind of a noob question. I just don't know how to word this process, so I'm not sure what to Google for. I'll put some C# code below that should explain what I'm trying to do. I just don't know how to do it in VB. Additionally, for future ref, if you could tell me what this process is called, it would be helpful to know. Thanks in advance for your help.

// Here is a simple class
public class FullName
{
    public string First { get; set; }
    public char MiddleInintial { get; set; }
    public string Last { get; set; }

    public FullName() { }
}

/* code snipped */

// in code below i set a variable equal to a new FullName 
// and set the values in the same line of code
FullName fn = new FullName() { First = "John", MiddleInitial = 'J', Last = "Doe" };
Console.Write(fn.First);  // prints "John" to console

As I mentioned earlier, I am drawing blanks on what to search for so sorry if this question is a repeat. I too hate reruns :) So, please link me somewhere else if you find something.


Solution:

So thanks to the help of one of our members, I have found that the keyword is With.

Dim fn As New FullName() With { .First = "John", .MiddleInitial = "J"c, .Last = "Doe" }
Console.Write(fn.First)  ' prints "John" to console

Upvotes: 8

Views: 15391

Answers (3)

Karmic Coder
Karmic Coder

Reputation: 17949

They are known as object initializers. You can find more information on them here.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564671

This is an Object Initializer.

The equivelent VB.NET code would be:

Dim fn = New FullName() With {.First = "John", .MiddleInitial = 'J', .Last = "Doe" }

The VB.NET reference is on MSDN.

Upvotes: 20

Konamiman
Konamiman

Reputation: 50313

This feature is named Object Initializers. See here: http://www.danielmoth.com/Blog/2007/02/object-initializers-in-c-30-and-vb9.html

Upvotes: 5

Related Questions