Domanda

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.)

È stato utile?

Soluzione

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://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/data-types/tuples

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top