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.
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
Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).
To create an object of a named class by using an object initializer. Begin the declaration as if you planned to use a constructor. Type the keyword With , followed by an initialization list in braces. In the initialization list, include each property that you want to initialize and assign an initial value to it.
There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.
Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable. File: TestStudent2.java.
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.
This feature is named Object Initializers. See here: http://www.danielmoth.com/Blog/2007/02/object-initializers-in-c-30-and-vb9.html
They are known as object initializers. You can find more information on them here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With