You Should Know About Anonymous Type in .NET!

Come from my prior technology which is Java, C# always make me “WOW” with its cool features that are not available in Java such as LINQ, Object Initializer and the one i am going to talk about, Anonymous Type.

anonymous type

Even, Indonesian java champion Frans Thamura stated that C# as language is cooler than Java and he said that unfortunately C# is running on top of CLR not JVM. Lol!.

anonymous type

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first (Class). This is not so common because we always require to write Class to encapsulate properties to hold values.

Example of anonymous type is given below

Above, you can see that book is used to encapsulate both Title and Auhtor and instead it is instantiated as a certain type it goes anonymous.

Some of you may get this question in mind,
“Okay, this is cool. But why should i use anonymous type instead of class type when it is more comfortable and common usage?”

Based on my experience the answer is “because anonymous type gives you option to select property that you are interested in, others just let it go”.

Consider following example. You have a class named Student to store information about student in your application.

Then somewhere in your code you want to populate students data and show it, let’s say windows form app. You will do something like this in the constructor of the form

Will have result like this
anonymous type

Actually you only interested in StudentId, FirstName and LastName property to be shown in the form, how to achieve it then?

Here anonymous type come to the rescue. Do some change below

anonymous type

As you can see anonymous type help us to select only property that we are interested in.Hope my little experience will help you and thank you for coming, spread the knowledge 😉

Facebook Comments
 

Agung Setiawan

Agung Setiawan adalah software engineer di BukaLapak.com, penulis sekaligus pecinta sastra, dan pembaca buku

 
Halo, perkenalkan saya Agung Setiawan.
Saya Software Engineer di BukaLapak.
Simak pemikian saya soal dunia Software Engineering via Twitter di @agungsetiawanmu dan facebook
Blog ini saya update seminggu sekali jadi sering-sering saja mampir
Mau belajar Vim bareng saya?
Belajar ngoding dari nol menggunakan PHP

2 thoughts on “You Should Know About Anonymous Type in .NET!

    1. Linq to Object, to SQL, to XML dll itu cuma data sourcenya aja yang berbeda
      to Object berarti sumber datanya dari object, biasanya List atau IQueryable bisa juga IEnumerable
      to SQL berarti sumber datanya SQL Server, kalau sekarang sih lebih baik pakai Entity Framework.

Leave a Reply

Your email address will not be published. Required fields are marked *