Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET equivalent of C# object initializer of an anonymous type

I'm not experienced with advanced features of .NET type system. I cannot find out of what type is zz (what can be written instead of var. Or is var the best choice here?)

string foo = "Bar";
int cool = 2;
var zz = new { foo, cool };    // Watches show this is Anonymous Type

but most importantly, how the equivalent can be achieved in VB.NET code (this is what I actually need).

Dim Foo As String = "Bar"
Dim Cool As Integer = 2
Dim zz = {Foo, Cool}    'This is not an equivalent of above, I'm getting an array

I have searched several C# sources, used code watches and learned about how zz looks internally but I'm unable to make next step.

(The purpose of my effort is something like this in VB.NET.)

like image 253
miroxlav Avatar asked May 08 '14 10:05

miroxlav


People also ask

Is there a VB.NET equivalent for C#' s operator?

The correct equivalent is the if() statement with 2 arguments.

Which is better VB.NET or C#?

When you will go for a job in Programming then C# will be the better choice. If you first want to learn then VB could be the better choice - it depends on what is better readable for you. In both cases : what you have to learn is not the programming-language - what you have to learn is the use of the .

What is dim in C#?

In VB, the Dim keyword is used to declare a variable. In C#, this intent is implicit in using a type to begin a statement. The var keyword in C# can be used in place of a type name, but it is still a strong type, and it requires that the variable be initialized on the same statement.

Which is not the operator in Visual Basic?

For numeric expressions, the Not operator inverts the bit values of any numeric expression and sets the corresponding bit in result according to the following table.


1 Answers

Your code would not even compile with OPTION STRICT set to ON which is highly recommended. No type can be derived from String + Int32. It would compile if you want an Object():

Dim zz As Object() = {Foo, Cool}

But you want to create an anonymous type, use New With:

Dim zz = New With {Foo, Cool}

http://msdn.microsoft.com/en-us/library/bb385125.aspx


With .NET 4.7 and Visual Basic 2017 you can also use ValueTuples with names:

Dim zz = (FooName:=foo, CoolName:=cool)    

Now you can access the tuple items by name:

int cool = zz.CoolName;

https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/data-types/tuples

like image 147
Tim Schmelter Avatar answered Sep 22 '22 14:09

Tim Schmelter