C# Object and Collection Initializers

C# Code Snippets Object and Collection Initializers
Share:

About

In this code snippet, we will learn how to use object and collection initializers in C#.

Initializers let you set any accessible property at the point of creation of an object or collection(without having to invoke the constructor). This can make it easier and faster to create objects/collections. And by faster, I mean faster for you to implement as a programmer not faster performance-wise.

Let’s see how to use initializers in the code example below.

Code:

using System;
using System.Collections.Generic;

namespace Initializers
{
    class Program
    {
        static void Main(string[] args)
        {
            //Object initializer.
            var MyObject = new MyClass { Number = 4, Text = "four" };
            
            //Collection initializer (used together with object initializer).
            List<MyClass> myList = new List<MyClass>() {
              new MyClass {Number = 1, Text = "one"},
              new MyClass {Number = 2, Text = "two"},
              new MyClass {Number = 3, Text = "three"}
            };
            
            //As you can see creating a new list of objects can be much quicker an easier using initializers compared to using the normal way.
        }
    }

    class MyClass
    {
        public int Number { get; set; }

        public string Text { get; set; }
    }
}
Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger