1. Back To Blog

.NET interview questions: - Different types anonymous and their practical use?

.NET interview questions: - Different types anonymous and their practical use?

Anonymous Type: - Anonymous Types help us to create an object without declaring its data type and also help us to create properties with good meaningful names. Since the name of the data type is not specified that the type is referred to as an Anonymous Type.

Let's first see in what kind of scenario Anonymous Type are applicable.

Suppose we have a simple string which has Customer's, FirstName, MiddleName, LastName and PhoneNumber like below code snippet.

Now, you would like to parse the data and take the data in to individual variables like below code snippet.

In order to parse data into individual variables, we have to create a function with "Out" parameters and have to use "Split" function like below code snippet.

Still now we have done with parsing the data.

Now just invoke this function from the main class like below code snippet.

ParseData(str, out strFirstName, out strMiddleName, out strLastName, out PhoneNumber);

Now, let just display the result for that just add the below code snippet.

Let's see how the result set look like.

The above code is nice its work's properly but the concern here is the code tidiness, in current scenario all the variables are individual variables in case if you want to parse the data around it would be very tedious job to do and it would make your code very lengthy and not be very easy to read.

So Anonymous Type helps to solve the above problem in simplified manner and making our code more readable and understandable.

Let's see how exactly Anonymous Type help to solve the above problem for that you just need to follow the following steps.

Step1: - create a new project Console Application for that Go To > New > File > Project > Windows > Select Console Application.

: - create a string variable containing data like below code snippet.

Step3: - create an Anonymous Type like below code snippet.

In the above code snippet you can see that we have created an Anonymous Type with FirstName, MiddleName, LastName, PhoneNumber and this is getting type casted to object because we cannot return Anonymous Type object outside the function straight forward. We need to type caste it like below code snippet.

Step4: - Now receive Anonymous Type in the main class like below code snippet and also display.

In the above code snippet as soon as you type CustomerInformation(.)(dot) the VS business intelligence will show properties like below diagram.

Now just run your application and will see the result like below diagram.

Also view following video on why anonymous types are better than tuples.

Get our tutorials on important .NET interview questions


Visit for author's more blog on interview questions and answers for Dotnet 

Shiv Prasad Koirala

Visit us @ www.questpond.com or call us at 022-66752917... read more

We are on Social