Home > database >  making instance of class in c#
making instance of class in c#

Time:12-22

in this code

using System;
namespace Hello
{
    class TestEmployee
    {
        static void Main()
        {
            Employee employee = new Employee();
            employee.salary = 1000;
            employee.bonus = 100;
            employee.CacalculateTotalPay();
            Console.ReadKey();
        }
    }
    class Employee
    {
        public double salary;
        public double bonus;
        public void CacalculateTotalPay()
        {
            Console.WriteLine(salary   bonus);
        }
    }
}

why we should make instance of a class with new when we declared the employee variables type with Employee class?

I didn't tried anything.

CodePudding user response:

When you declare a variable for a class without a new instance, like this:

Employee employee;

you don't actually have an instance of the class yet. There is no Employee object here. What you have is a variable with the potential to refer to a class instance. Initially there isn't anything there; only the potential... it is a null reference. Therefore we might also create a new instance of the type and assign that new instance to our variable.

Employee employee = new Employee();

You could avoid this by making the Employee type static. Then, instead of declaring a variable at all you would refer to its members via the type name (ie Employee.salary). However, that's limiting. If you refer to the members via type name you would have no way to distinguish one employee from another, and you likely expect to have many more than just the one employee.

Therefore we do not use static and instead create new instances so that each instance can represent a different employee.

This can be confusing for new programmers, because the first exposure to code is via a class with a static Main() method, where you did not need to create an instance, and with primitive types like int and string that have support in the language so you don't need to use the new operator. It may be some time before you progress far enough to need to worry about object instances. But rest assured, over time instances are the norm, and static and struct will be less common.

It is important to come to terms with the difference between object instances, references, variables, and types (classes/structs). Those are four different kinds of thing, and it is difficult to write effective code without understanding how they relate to each other.

  • Related