Saturday, April 24, 2021

C# Object Initializer and Collection Initializer Examples



using System;
using System.Collections.Generic;

namespace Console_Object_Initializer_Examples
{
    public class Cat
    {
        // Auto-implemented properties of Cat.
        public int Age { get; set; }
        public string Name { get; set; }
        //parameterless constructor
        public Cat()
        {
        }
        //parameterized constructor
        public Cat(string name)
        {
            this.Name = name;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            /*
              * The object initializers syntax allows you to create an instance, and after that it assigns the newly created object, with its assigned properties, to the variable in the assignment.
              */
            
            //Object Initializer Examples
            Cat cat = new Cat { Age = 2, Name = "Mikey" };
            Console.WriteLine(cat.Name + " " + cat.Age.ToString());
            Cat AnotherCat = new Cat("Billy") { Age = 4 };
            Console.WriteLine(AnotherCat.Name + " "+ AnotherCat.Age.ToString());
            
            //Object Initializer of Anonymous type Examples
            var book = new { Genre = "Fiction",  Price=300};
            Console.WriteLine(book.Genre + " " + book.Price.ToString());

            //Object Initializer inside Collection Initializer
            List cats = new List
            {
                new Cat{ Name = "Billy", Age=3 },
                new Cat{ Name = "Pussy", Age=5 },
                new Cat{ Name = "Meaun", Age=4 }
            };

            foreach (var ct in cats)
            {
                Console.WriteLine(ct.Name + ", "+ ct.Age);
            }

        }
    }
}
OUTPUT
Mikey 2
Billy 4
Fiction 300
Billy, 3
Pussy, 5
Meaun, 4

No comments:

Post a Comment

Hot Topics