0

I want to reach the same result as I obtain in C# with this syntax, but in VB.NET:

// This is my generic object (coming from Json parsing!):
var genericContent = new { Name = "name1", Value = 0 };

// I would like to have a generic list, created by this generic item:
var myList = (new[] { genericContent }).ToList();

// So, I can add any other generic items (with the same structure)...
myList.Add(new { Name = "name2", Value = 1 });

// And treat them as a normal list, without declaring the class!
return myList.Count;

...so, I just want to create a generic array in VB.

In C# it works well, but I don't kwon this VB.NET syntax...

I'm using .NET framework 3.5!

Thank you!

3
  • 'Aight, and what have you tried so far? VS provides a very handy intellisense, that can really help if used properly... Commented Aug 22, 2012 at 11:53
  • possible duplicate of Does VB.NET 2010 support arrays of anonymous objects? Commented Aug 22, 2012 at 11:56
  • 1
    @BigYellowCactus, you're right, but no one said he doesn't have access to Google, right? If he had at least tried to combine intellisense + google, he'll have the answer in no time without wasting our and his time here, don't you think? Now his question looks like - hey, I need THIS, but I don't want to do it, so do it for me people! Commented Aug 22, 2012 at 12:04

2 Answers 2

3

No problem here:

Dim genericContent = new with { .Name = "name1", .Value = 0 }
Dim myList = {genericContent}.ToList()
myList.Add(new with { .Name = "name2", .Value = 1 })

At least in .Net 4.0 (VB.Net 10.0).

For earlier versions: No, not possible without a helper method.

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

2 Comments

Is it working with .NET framework 3.5? I was not sure...in this case is much more compact!
Thank you...but this is not running for me...it gives an error and I cannot compile!!
0

I think with that framework there's no compact syntax for that, as in C#...

Try using this way...

Declare a method like this (shared is better I think):

Public Shared Function GetArray(Of T)(ByVal ParamArray values() As T) As T()
    Return values
End Function

So you can create an array passing a generic parameter, than with LINQ should be easy to create a generic list:

Dim genericContent = New With { Name = "name1", Value = 0 }

Dim myList = (GetArray(genericContent)).ToList()

myList.Add(New With { Name = "name2", Value = 1 })

return myList.Count

Comments

Your Answer

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