UrbanPro
true

Learn C# .NET from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

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

.Net is not tough just it requir skill build
Hello friends which one is better java or .net ? Well you need to know both to make a right full argument. My advice would be pick any one get skilled on that and then learn second one. I believe by...

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':...

What Is The Difference In For...Loop And Foreach Loop?
Loop is very important in C# Programing language. Loop is call iteration statement, loops are used for executing the repeated task. 1. For...Loop: The for…loop executes a statement or a block...
N

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

What Is An Array? Explain Its Type.
Array: Array is a collection of similar type of data in an array varaiable. Array start with Zero Index and maximum length of array is total element - 1. i.e., Suppose n is the length of array, total element...
N
X

Looking for C# .NET Classes?

The best tutors for C# .NET Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn C# .NET with the Best Tutors

The best Tutors for C# .NET Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 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 7.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