true

Find the best tutors and institutes for C# .NET

Find Best C# .NET

Please select a Category.

Please select a Locality.

No matching category found.

No matching Locality found.

Outside India?

Search for topics

Object Initializers And Collection Initializers: A Syntactic Sugar In C# 3.0

Debendra Dash
12/10/2017 0 0

i. Introduction:

Object initializers and Collection initializers are part of C# 3.0.These two concepts add a flexibility, readability, and maintainability in C#. As we are C# developers, we should know how and in which situations we can use these two concepts and inprove our programming logic. Before going deep, dive into object and collection initializers. We will check what are these Syntactic Sugars.

ii. Syntactic sugar in programming:

Syntactic sugar, or syntax sugar, is considered as a "shortcut" provided by the language, which reduces the amount of code that must be written in a particular situation.

Syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.

The main benifits of using syntatic sugar in programming are:

  1. Avoid lot of keystrokes,The efficiency of software programs is sometimes measured by the number of keystrokes it requires to write a specific function.

  2. Easy to readable and maintainable.

  3. Time saving approach.

Let's see an example of  how we can use syntactic sugar in our program. Let's consider an example of normal IF-ELSE conditional statement:

class Program
{
static void Main(string[] args)
{
int x = 20, y = 10;
if (x>y)
{
Console.WriteLine(x);

}
else
{
Console.WriteLine(y);

}
Console.ReadLine();

}
Now, let's use Ternary operators and see how much key strokes we can prevent using Ternary operator.
class Program
{
static void Main(string[] args)
{
int x = 20, y = 10;
var result = x > y ? x : y;
Console.WriteLine(result);
Console.ReadLine();

}
So, in this way, we can say that by using ternary operator, we can achive syntactic sugar in our programming. Now, let's come to our main topic about Object Initialization and Collection Initialization.
So in programming, initialization is the assignment of an initial value for a data object or variable.

iii. Object Initializers:
Before going toward object initializers, let us see how we are initialising a object in C# 2.0:
public class Employee
{
public string Name { get; set; }
public int Id { get; set; }
public string Department { get; set; }
public int salary { get; set; }
}
class Program
{
static void Main(string[] args)
{
Employee emp=new Employee();
emp.Name = "Kumar";
emp.Department = "IT";
emp.Id = 101;
emp.salary = 80000;
Console.ReadLine();

}
}

Let's see how we can do that using object initializer in C# 3.0.

Write the same program using Object Initializer:
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee {Name = "Kisan",Id = 55,Department = "IT",salary = 20000};

}
}
It seems that we have saved a lot of Key strokes using this Object Initializer. So, this is also considered as a "Syntactic Sugar".
iv. Collection Initializers:
Collection Initializers are used to initialize a collection in a planned and advance manner to avoid lot of Key strokes:
namespace syntax_sugar
{
public class Employee
{
public string Name { get; set; }
public int Id { get; set; }
public string Department { get; set; }
public int salary { get; set; }
}
class Program
{
static void Main(string[] args)
{

List liemp=new List();
Employee emp = new Employee();
emp.Name = "Kumar";
emp.Department = "IT";
emp.Id = 101;
emp.salary = 80000;
liemp.Add(emp); //one object is added in the list

Employee emp1 = new Employee();
emp1.Name = "Abdul";
emp1.Department = "IT";
emp1.Id = 1010;
emp1.salary = 80000;
liemp.Add(emp1); //Second object is added in the List

}
}

Let's see how we can improve our coading quality using collection Initializers. Consider the following program for reference:

static void Main(string[] args)
{

List liemp = new List
{
new Employee {Name = "Kumar",Id = 101,Department = "IT",salary = 80000},
new Employee {Name = "Abdul",Id = 1010,Department = "IT",salary = 80000}

};
}

Conclusion:

Here, our main intention is to make you aware about Collection Initialization and Object Initiallization which are two important concepts discovered in C# 3.0, and let you know how these two important concepts are considered as syntactic sugar in progromming.
Hope you liked this article. If you have any doubts  and suggestation, please do comment so that I can update.
0 Dislike
Follow 2

Please Enter a comment

Submit

Other Lessons for You

Facebook Analytics
Assume how the Facebook application will store the millions of customer's record in real-time: facebook = { 'jose': { 'name': 'jose', 'age': 33, 'hobby': , # cricket,football 'mobile': 1111111111, 'email':...

Logeswaran | 03/09/2019

0 0
0

Multi-core CPU utilization using Task Parallel Library in c#
Nowadays, we are using multiple core systems. We must write our .NET applications in such a way that we must utilise the complete computing power of the machine. The parallel task library(TPL) allows...

Ketan Agnihotri | 12/01/2019

0 0
0

Why a function in C# requires "Return type"??
- Basically , a Method is a piece of code used for the re-usability purpose. - Method is of 2 types Function and Procedure - Function is a method which returns a value to the calling place Function...

Raga Deepthi G. | 25/09/2018

0 0
0

What are various validator in ASP.NET 2.0 and features common in all validation control in ASP.NET
Control to validate an error message. Are common feature in all the controls.Various validators are requiredfeild validator ,compare validator ,regular expression validator,custom validator,range validator...

Suprio Dutta | 29/06/2018

0 0
0

What are Various Types of Exception in C#
ArgumentException, ArgumentNullException, and ArgumentOutOfRangeException. NullReferenceException, IndexOutOfRangeException, SQL exceptions Stack Overflow Exception, Invalid Castexception ArgumentException...

Suprio Dutta | 28/06/2018

0 0
0
X

Looking for C# .NET Classes?

Find best tutors for C# .NET Classes by posting a requirement.

  • Post a learning requirement
  • Get customized responses
  • Compare and select the best

Looking for C# .NET Classes?

Find best C# .NET Classes in your locality on UrbanPro

Post your learning requirement

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 25 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 6.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more