C# Object Initializer

How to initialize objects by using an object initializer

You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.

The following examples show how to use object initializers with named objects.

public class Program
{
    public static void Main()
    {

        Student s1 = new Student()
        {
            Name = "Sam",
            City = "MYS"
        };

        Student s2 = new Student()
        {
            ID = 183
        };

        Student s3 = new Student()
        {
            ID = 116,
            Name = "Jim",
            City = "TKY",
        };

        Console.WriteLine(s1.ToString());
        Console.WriteLine(s2.ToString());
        Console.WriteLine(s3.ToString());
    }
 

    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
      
    }
}

Last updated