For me the benefit of using them is that
- You don't have to maintain another class for a small local calculation.
- You make the code more readable, concentrating on the tasks instead of the syntax.
- You don't have a class someone can abuse for their own purposes.
The example below introduces a couple of other ideas such as Linq but we can ignore them for now. From a list of Dogs the name property alone is selected (mapped) into an anonymous object and returned as a collection.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Imports System.Text | |
Imports Microsoft.VisualStudio.TestTools.UnitTesting | |
Public Class Dog | |
Public Property Id As Integer | |
Public Property Name As String | |
Public Property Age As Integer | |
End Class | |
<TestClass()> | |
Public Class GivenAListOfDogs | |
Private _dogs As IList(Of Dog) | |
<TestInitialize()> | |
Public Sub Setup() | |
Me._dogs = New List(Of Dog) | |
Me._dogs.Add(New Dog() With {.Id = 1, .Name = "Bob", .Age = 12}) | |
Me._dogs.Add(New Dog() With {.Id = 2, .Name = "Bill", .Age = 2}) | |
Me._dogs.Add(New Dog() With {.Id = 3, .Name = "Brady", .Age = 5}) | |
End Sub | |
<TestMethod()> | |
Public Sub TheyCanBeSelectedIntoACollectionOfAnonymousObjects() | |
Dim dogs = _dogs.Select(Function(d) New With {.Name = d.Name}) | |
Dim bob = dogs.First() | |
Assert.AreEqual(bob.Name, "Bob") | |
End Sub | |
End Class |
If I recall, what the compiler nicely does for you is to create a class for you in the background that you don't see. We can check this by using the ILDASM tool that comes with Visual Studio. If you see the picture below after I load my dll into there, the anonymous type has been created as a class called AnonymousType_0`1<T0> and you can see the property Name on there as well. It's worth noticing here that the property Name is readonly meaning that the anonymous type is immutable once you have created it. Immutability is something very dear to me being a fan of F# as well as BASIC languages.
0 comments:
Post a Comment