C# - Classes

Classes

A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable.

The General Form of a Class

A class is created by use of the keyword class. Here is the general form of a simple class definition that contains only instance variables and methods:

class classname {
    // declare instance variables
    access type var1;
    access type var2;
    // ...
    access type varN;
    // declare methods
    access return-type method1(parameters) {
        // body of method
    }
    access return-type method2(parameters) {
        // body of method
    }
    // ...
    access return-type methodN(parameters) {
        // body of method
    }
}

Fields

A field is a variable that is a member of a class or struct. For example:

    class date
    {
        int dd, mm, yy;
    }

Methods

A method performs an action in a series of statements. A ,method can receive input data from the caller by specifying parameters and output data back to the caller by specifying a return type. A method can specify a void return type, indicating that it doesn’t return any value to its caller. A method can also output data back to the caller via ref/out parameters.

    class date
    {
        int dd, mm, yy;
        public void setDate(int day,int month,int year)
        {
            dd = day;
            mm = month;
            yy = year;
        }
        public void printdate()
        {
            Console.WriteLine("{0}/{1}/{2}", dd, mm, yy);
        }
        public int getDay()
        {
            return dd;
        }
        public int getMonth()
        {
            return mm;
        }
        public int getYear()
        {
            return yy;
        }
        public void setDay(int day)
        {
            dd = day;
        }
        public void setMonth(int month)
        {
            mm = month;
        }
        public void setYear(int year)
        {
            yy = year;
        }
    }

How Objects Are Created

The new operator dynamically allocates (that is, allocates at runtime) memory for an object and returns a reference to it. This reference is then stored in a variable. Thus, in C#, all class objects must be dynamically allocated.

  date dob=new date();

As you might expect, it is possible to separate the declaration of dob from the creation of the object to which it will refer, as shown here:

    date dob; // declare reference to object
    dob = new date(); // allocate a Building object

Constructors

A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type. The general form of a constructor is shown here:

    access class-name(param-list) 
    {
        // constructor code
    }

Typically, you will use a constructor to give initial values to the instance variables defined by the class or to perform any other startup procedures required to create a fully formed object. Also, usually, access is public because constructors are normally called from outside their class. The param-list can be empty, or it can specify one or more parameters.

All classes have constructors, whether you define one or not, because C# automatically provides a default constructor that causes all member variables to be initialized to their default values. For most value types, the default value is zero. For bool, the default is false. For reference types, the default is null. However, once you define your own constructor, the default constructor is no longer used.

Here is a simple example that uses a constructor:

// A simple constructor.
using System;
class MyClass {
    public int x;
    
    //constructor
    public MyClass() {
        x = 10;
    }
}
class ConsDemo {
    static void Main() {
            MyClass t1 = new MyClass();
            MyClass t2 = new MyClass();
            Console.WriteLine(t1.x + " " + t2.x);
    }
}

Parameterized Constructors

A constructor with at least one parameter is called a parametrized constructor. The advantage of a parametrized constructor is that you can initialize each instance of the class to different values.

// A parameterized constructor.
using System;
class MyClass {
    public int x;
    
    public MyClass(int i) {
        x = i;
    }
}
class ParmConsDemo {
    static void Main() {
        MyClass t1 = new MyClass(10);
        MyClass t2 = new MyClass(88);
        Console.WriteLine(t1.x + " " + t2.x);
    }
}

The output from this program is shown here:

    10 88

Copy Constructor

The constructor which creates an object by copying variables from another object is called a copy constructor. The purpose of a copy constructor is to initialize a new instance to the values of an existing instance.

    Syntax
public employee(employee emp)
{
    name=emp.name;
    age=emp.age;
}
The copy constructor is invoked by instantiating an object of type employee and ing it the object to be copied.
Example
    employee emp1 = new employee("rahul", 23);  // Create a new employee object.
    employee emp2 = new employee(emp1);          // here is emp1 details is copied to emp2.

Garbage Collection and Destructors

C#’s garbage collection system reclaims objects automatically—occurring transparently, behind the scenes, without any programmer intervention. It works like this: When no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object is eventually released and collected. This recycled memory can then be used for a subsequent allocation.

Garbage collection occurs only sporadically during the execution of your program. It will not occur simply because one or more objects exist that are no longer used. Thus, you can’t know, or make assumptions about, precisely when garbage collection will take place.

It is possible to define a method that will be called just prior to an object’s final destruction by the garbage collector. This method is called a destructor, and it can be used in some highly specialized situations to ensure that an object terminates cleanly.

Destructors have this general form:

    ~class-name( ) {
        // destruction code
    }

Here, class-name is the name of the class. Thus, a destructor is declared like a constructor except that it is preceded with a ~ (tilde). Notice it has no return type and takes no arguments.

The this Keyword

The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.

The following are common uses of this:

  • To qualify members hidden by similar names, for example:
            public Employee(string name, string alias)
            {
                // Use this to qualify the fields, name and alias:
                this.name = name;
                this.alias = alias;
            }
  • To pass an object as a parameter to other methods, for example:
    CalcTax(this);  

Static in C#

In C#, data members, member functions, properties and events can be declared either as static or non-static.

Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events.

Static Data Members

A C# class can contain both static and non-static members. When we declare a member with the help of the keyword static, it becomes a static member.

When a member is declared static, it can be accessed before any objects of its class are created and without reference to any object. You can declare both methods and variables to be static.

You can't use this keyword with static, as it will not initialize. Static members are shared level and are not initiated.

Static constructor

Static Constructor is used to initialize static data members of the class.

Static constructor can't be parameterized. Static constructor doesn't have any access modifier because it doesn't have message passing and used during domain processing.

Static Properties

Static properties are used to get or set the value of static data members of a class.

Static methods

Static methods are shared methods. They can be called with the class name and static method name only. No need of instance to call static methods. Static methods only use static data members to perform calculation or processing.

Static Classes

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example:

UtilityClass.MethodA();  

A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For example, in the .NET Framework Class Library, the static System.Math class contains methods that perform mathematical operations, without any requirement to store or retrieve data that is unique to a particular instance of the Math class. That is, you apply the members of the class by specifying the class name and the method name, as shown in the following example.

double dub = -3.14;  
Console.WriteLine(Math.Abs(dub));  
Console.WriteLine(Math.Floor(dub));  
Console.WriteLine(Math.Round(Math.Abs(dub)));  
  
// Output:  
// 3.14  
// -4  
// 3