8

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
1
  • 2
    I guess you tagged this wrong. The question is actually about Visual Basic, not C#. Commented Nov 11, 2009 at 18:45

3 Answers 3

20

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.