Saturday, 18 August 2018

C#: Object initializer syntax

C# provides Object initializer syntax to define an object.

Example
         Employee emp1 = new Employee
        {
            Id = 1,
            FirstName = "Hari krishna",
            LastName = "Gurram"
        };

Following is the complete working application.

Program.cs
using System;

class Employee
{
    private int id;
    private String firstName;
    private String lastName;

    public String getName()
    {
        return firstName + "," + lastName;
    }

    public int Id
    {
        get
        {
            return id;
        }

        set
        {
            id = value;
        }
    }

    public string FirstName
    {
        get
        {
            return firstName;
        }

        set
        {
            firstName = value;
        }
    }

    public string LastName
    {
        get
        {
            return lastName;
        }

        set
        {
            lastName = value;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Employee emp1 = new Employee
        {
            Id = 1,
            FirstName = "Hari krishna",
            LastName = "Gurram"
        };
        
        Console.WriteLine("Id : {0}", emp1.Id);
        Console.WriteLine("First Name : {0}", emp1.FirstName);
        Console.WriteLine("Last Name : {0}", emp1.LastName);
    }
}


Output

Id : 1
First Name : Hari krishna
Last Name : Gurram



Previous                                                 Next                                                 Home

No comments:

Post a Comment