How to initialize an object in C Sharp

Learn how to initialize an object in C# with simple example.

We can initialize an object in C# programs using constructor. We need to create a parameterized constructor in the class that can accept arguments. The class fields will be initialized with these parameters in the constructor.

When you create an object with arguments, the class constructor in C# program will be automatically called and fields will be initialized.

Let’s understand object initialization by an example,

Consider a class Person that has 3 fields i.e. name, age and gender. We will create a constructor with 3 parameters as below and initialize the class members with these parameters.

Here is an example of constructor with 3 parameters. All fields are initialized into it. Note that “this” keyword before fields has been used, so, we can know that they are class fields. In fact, to differentiate parameters and class fields.

public Person(String name, int age, String gender){
		
		this.name = name;
		this.Age = age;
		this.gender = gender;
		
	}

When we create object of the class as below, the above constructor will be called automatically, and the class members will be initialized.

Person John = new Person(“John”,30,”M”);

Example of how to initialize an object in C#

class Person
    {

        // properties of a person
        private String name;
        private int Age;
        private String gender;

        // Constructor : initialize all class fields

        public Person(String name, int age, String gender)
        {

            this.name = name;
            this.Age = age;
            this.gender = gender;

        }

        public String getName()
        {
            return name;
        }

        public int getAge()
        {
            return Age;
        }

        public String getGender()
        {
            return gender;
        }

    }
 
    
   /*
 * Test objects initialization.
 */ 
    class Program
    {
        static void Main(string[] args)
        {
            Person scott = new Person("Scott", 30, "M");

            Console.WriteLine("Name: " + scott.getName());
            Console.WriteLine("Age: " + scott.getAge());
            Console.WriteLine("Gender: " + scott.getName());
        }
    }

Output
Name: Scott
Age: 30
Gender: Scott

Related Posts