CSharp - Type Creation Object Initializers

Introduction

You can initialize accessible fields or properties via an object initializer.

For example, consider the following class:

class Person
{
       public string Name;
       public bool CanSpeakJava;
       public bool CanSpeakCSharp;

       public Person () {}
       public Person (string n) { Name = n; }
}

Using object initializers, you can instantiate Person objects as follows:

parameterless constructors can omit empty parentheses

Person b1 = new Person { Name="Bo", CanSpeakJava=true, CanSpeakCSharp=false };
Person b2 = new Person ("Bo"){ CanSpeakJava=true, CanSpeakCSharp=false };

Demo

using System;
class MainClass//from  ww w  .  j  a v a  2 s .  com
{
   public static void Main(string[] args)
   {

        Person b1 = new Person { Name="Bo", CanSpeakJava=true, CanSpeakCSharp=false };
        Person b2 = new Person ("Bo"){ CanSpeakJava=true, CanSpeakCSharp=false };
        
        Console.WriteLine(b2.Name);
        Console.WriteLine(b2.CanSpeakJava);
        Console.WriteLine(b2.CanSpeakCSharp);

   }
}
class Person
{
       public string Name;
       public bool CanSpeakJava;
       public bool CanSpeakCSharp;

       public Person () {}
       public Person (string n) { Name = n; }
}

Result

Related Topics