Anonymous Type Differs in C# and VB.NET

Have you Observed anonymous types closely in c# as well as VB.NET ?

Check the below sample sourcecode

In VB.NET

 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim PersonData As New Dictionary(Of String, Integer)

        PersonData.Add("Ilayathalapathy Vijay", 51)
        PersonData.Add("Ultimate Star Ajithkumar", 49)
        PersonData.Add("SuperStar Rajnikanth", 100)

        Dim MoreThan100MoviesHero = (From m In PersonData
                                 Where m.Value < 50
                                         Select New With
                                                {m.Key, m.Value}).First()

        MoreThan100MoviesHero.Value = 50
        MessageBox.Show(MoreThan100MoviesHero.Key & " has acted in around " & MoreThan100MoviesHero.Value & " Movies")
    End Sub

In C#

 private void Form1_Load(object sender, EventArgs e)
        {
            Dictionary<string, int> PersonData = new Dictionary<string, int>();
            PersonData.Add("Ilayathalapathy Vijay", 51);
            PersonData.Add("Ultimate Star Ajithkumar", 49);
            PersonData.Add("SuperStar Rajnikanth", 100);

            var MoreThan100MoviesHero = (from m in PersonData
                                     where m.Value < 50
                                             select new { m.Key, m.Value }).FirstOrDefault();
            MoreThan100MoviesHero.Value = 200;

        }

Try compiling the VB it should work , but when you try compiling the same c# code it should give you an compiler error

“Property or indexer ‘AnonymousType#1.Value’ cannot be assigned to — it is read only ”

Interesting isn’t it ?

When an anonymous type is used in C# , it is by default  created with read-only properties. You can’t assign the values to later after its construction .

But in VB.NET , this is possible :)
If you want the Anonymous properties to be readonly in VB.NET , you must include the heyword key in the query like the below example

  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim PersonData As New Dictionary(Of String, Integer)

        PersonData.Add("Ilayathalapathy Vijay", 51)
        PersonData.Add("Ultimate Star Ajithkumar", 49)
        PersonData.Add("SuperStar Rajnikanth", 100)

        Dim MoreThan100MoviesHero = (From m In PersonData
                                 Where m.Value < 50
                                         Select New With
                                                {Key m.Key, Key m.Value}).First()

        MoreThan100MoviesHero.Value = 50
        MessageBox.Show(MoreThan100MoviesHero.Key & " has acted in around " & MoreThan100MoviesHero.Value & " Movies")
    End Sub

 

References

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply