Class & Objects in C#

Class
 
A class is the most powerful data type in C#. Like structures, a class defines the data and behavior of the data type. It is nothing but a variable of type Object. Programmers can create objects that is called instance of a class. Unlike structures, classes support inheritance, a fundamental part of object-oriented programming. A class has more than one object.
 
Example:
 
private class example
{
	.
	.
}
 
Object
 
• An object is an instance of a class… This relationship is similar to that of a guidelines and a product.
 
img
 
Example:
 
example objexample = new example();
 
objexample is the object or instance of the class example.
 
Access Modifiers
 
Access modifiers are keywords used to specify the declared accessibility of a member or a type. There are five access modifiers in C#::
 
• public (There is no restrictions to access).

• private (There is limited access access is limited to within the class definition; this is the default access modifier type if none is formally specified).

• protected (There is limited access access is limited to within the class definition and any class that inherits from the class).

• internal (Access is limited exclusively to classes defined within the current project assembly).

• protected internal (Available only to the current class, derived classes, or classes in the current assembly)

 
Public is usable to everyone. A public member can be accessed using an instance of a class or an object, by a class’s internal code, and by any children of a class.
 
img
 
Private is hidden and usable only by the class itself. No code using a class instance can access a private member directly and neither can a children class.
 
img
 
Protected members are similar to private ones in that they are accessible only by the containing class. However, protected members also may be used by a children class. So members that are likely to be needed by a children class should be marked protected.
 
img
 
Internal/Friend is public to the entire application but private to any outside applications. Internal is useful when you want to allow a class to be used by other applications but reserve special functionality for the application that contains the class. Internal is used by C# and Friend by VB .NET.
 
img
 
Protected Internal may be accessed only by a children class that’s contained in the same application as its base class. You use protected internal in situations where you want to deny access to parts of a class functionality to any children classes found in other applications.
 
img
 
Create a class
 
You can create classes in C# with the class statement:
 
[attributes] [modifiers] class identifier [:base-list] { class-body }[;]
 
Here are the parts of this statement:
 
• attributes (Optional)—Attributes hold additional declarative information.

• modifiers (Optional)—The allowed modifiers are new, static, virtual, abstract, override, and a valid combination of the four access modifiers.

• identifier—The class name.

• base-list (Optional)—A list that contains the base class and any implemented interfaces, separated by commas.

• class-body—Declarations of the class members.

 
Note: The semicolon after a class declaration is optional in C#, unlike C++.
 
Example:
 
class  example
{
static void main()
{
System.Console.WriteLine("Hello from C#.");
}
}
 
The above example contains all codes in one class i.e. example. But there’s nothing to stop you from creating other classes in the same file. For example, here, we’ve added another class, sum, with one method, Addnum, which adds two integers and returns their sum:
 
class example
{
	static void Main()
 	{
  .
  .
  .
 	}
}

class sum
{
 	public long Addnum(int value1, int value2)
 	{
  		return value1 + value2;
 	}
}
 
A new class has been created—the sum class. To put that class to use, simply have to create an object of that class.
 
Creating Objects
 
To creating an object, also called an instance of a class, you use the ‘new’ keyword. We’ve seen how this process works; you can see how we create a new object of the sum class in example class, and use that object’s Addnum method to add 2 and 3.
 
Note the parentheses after sum in the statement sum objsum = new sum();. These parentheses are necessary when you use the new keyword. They let you pass data to a class’s constructor, the special method that lets you initialize the data in a class.
 
Example:
 
class example
{
	static void Main()
 	{
  sum objsum = new sum();
  System.Console.WriteLine("2 + 3 = {0}", objsum.Addnum(2, 3));
 	}
}

class sum
{
 	public long Addnum(int value1, int value2)
 	{
  	return value1 + value2;
 	}
}
 
Here’s what you see when you run this example:
 
C:\>example
2 + 3 = 5
 
Constructor
 
A constructor is a class member function in C++ and C# that has the same name as the class itself. The purpose of the constructor is to initialize all member variables when an object of this class is created.
 
Writing a constructor in the class is very simple. you have a look at the following sample:
 
public class myconstructorclass
{
	public myconstructorclass ()
	{
		// This is the constructor method.
	}
	// rest of the class members goes here.
}
 
When the object of this class is instantiated this constructor will be executed. Something likes this:
 
myconstructorclass obj = new myconstructorclass ()
// At this time the code in the constructor will be executed
 
Static Constructor
 
C# provides a special type of constructor known as static constructor. This constructor initializes only the static data members when the class is loaded at firsttime. Always keep in mind that, like any other static member functions, static constructors can’t access non-static data members directly.
 
The name of a static constructor must be the name of the class and even they don’t have any return type. The keyword static is used to differentiate the static constructor from the normal constructors. The static constructor can’t take any arguments. That means there is only one form of static constructor, without any arguments. In other way it is not possible to overload a static constructor.
 
We can’t use any access modifiers along with a static constructor.
 
Example
 
using System;
class staticconstructor
{
  	static staticconstructor ()
      {
 		Console.WriteLine("static constructor");
 	}
}
class MyClient
{
 	public static void Main()
 	{
 		staticconstructor c;
 		Console.WriteLine("UJJWAL");
 		c = new staticconstructor ();
 	}
} 
 
The output of the above program is
 
UJJWAL static constructor
 
Note: that static constructor is called when the class is loaded at the first time. However, we can’t predict the exact time and order of static constructor execution. They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class is called.
 
Like non-static constructors, static constructors can’t be chained with each other or with other non-static constructors. The static constructor of a base class is not inherited to the derived class.
 
Private Constructors
 
In C#, constructors can be declared as public, private, protected or internal. When a class declares only private constructors, it is not possible other classes to derive from this class or create an instance of this class.
 
Private constructors are commonly used in classes that contain only static members. However a class can contain both private and public constructor and objects of such classes can also be created, but not by using the private constructor.
 
The following is a valid program in C#
 
// C# constructor both private & public
using System;
class PrivateConstructor
{
 	//private constructor with integer arguments
private PrivateConstructor (int i, int j) 
 	{
 		Console.WriteLine("constructor with 2 integer arguments");
 	}
 	//private constructor with no arguments
public PrivateConstructor ()
 	{
 		Console.WriteLine("no argument constructor"); 
 	}
}
class MyClient
{
 	public static void Main()
 	{
 	 	PrivateConstructor c3 = new PrivateConstructor ();
 	}
}
 
However the following program do not compile since it contain only private constructors
 
// C# constructor only private will show compilation error.
 
using System;
class PrivateConstructor
{
 	private PrivateConstructor ()
 	{
 		Console.WriteLine("no argument constructor"); 
 	}
}
class MyClient
{
 	public static void Main()
 	{
 		PrivateConstructor c3 = new PrivateConstructor ();
 	}
}
 
Constructor Overloading
 
Just like member functions, constructors can also be overloaded in a class. The overloaded constructor must differ in their number of arguments and/or type of arguments and/or order of arguments.
 
The following program shows the overloaded constructors in action.
 
// C# constructor overloading
using System;
class constructoroverload
{
 	public constructoroverload (int i, int j) 
 	{
 		Console.WriteLine("Constructor with 2 integer arguments");
 	}

 	public constructoroverload (double i, double j) 
 	{
 	 	Console.WriteLine("Constructor with 2 double arguments");
 	}
 	public constructoroverload ()
 	{
 	 	Console.WriteLine("No argument constructor"); 
 	}
}
class MyClient
{
 	public static void Main()
 	{
 	 	constructoroverload c1 = new constructoroverload (20, 25);
// displays 'Constructor with 2 integer arguments'
 		constructoroverload c2 = new constructoroverload (2.5, 5.9);
 		// displays 'Constructor with 2 double arguments'
 		constructoroverload c3 = new constructoroverload (); 
//displays 'No argument constructor'
 	}
} 
 
Output
 
Constructor with 2 integer arguments
Constructor with 2 double arguments
No argument constructor
 
Constructor Chaining
 
The entire above program shows that C# supports constructor overloading. In C#, even one constructor can invoke another constructor in the same class or in the base class of this class. This is what is known as constructor chaining.A special type of syntax is used for constructor chaining as follows.
 
// C# constructor chaining 
using System;
class ConstructorChain
{
 	private ConstructorChain ()
 	{
 		Console.Write("1"); 
 	}
 	private ConstructorChain (int x):this()
 	{
 		Console.Write("2"); 
 	}
 	public ConstructorChain (int x, int y):this(10)
 	{
 		Console.Write("3"); 
 	}
}
class MyClient
{
 	public static void Main()
 	{
 		ConstructorChain c = new ConstructorChain (10,20); // Displays 123
 	}
} 
 
Output
 
123
 
In the above program the ConstructorChain (int x, int y) invokes the ConstructorChain (int x) constructor by using a special syntax ‘:’ this (arguments), which in turn invokes the ConstructorChain () constructor.
 
Constructors & Inheritance
 
Both static and non-static constructors are not inherited to a derived class from a base class. However, a derived class non-static constructor can call a base class non-static constructor by using a special function base(). It is possible to invoke both default and parameterized constructors of the base class from the derived class.
 
If we don’t call the base class constructor explicitly, the derived class constructor will call the default constructor of the base class implicitly when an object of the derived class is created. This is shown in the program given below.
 
// C# Implicit call of base class default constructor
using System; 
class Base
{
 	public Base()
 	{
 		Console.WriteLine("Base constructor");
 	}
}
class Derived : Base //Inherit base class
{

}
class MyClient
{
 	public static void Main()
 	{
 		Derived d1 = new Derived(); //Displays 'Base constructor'
 	}
} 
 
Output
 
Base constructor
 
We can also call a base class constructor explicitly by using base () as shown below.
 
// C# Implicit call of base class default constructor 
using System; 
class Base
{
 	//Constructor with no arguments
public Base()
 	{
 		Console.WriteLine("BASE 1");
 	}
 	//Constructor with no arguments
public Base(int x)
 	{
 		Console.WriteLine("BASE 2");
 	}
}
class Derived : Base
{
 	public Derived():base(10)
 	{
 		Console.WriteLine("DERIVED CLASS");
 	}
}
class MyClient
{
 	public static void Main()
 	{
 		Derived d1 = new Derived();
 	}
}
 
This program outputs
 
BASE 2
DERIVED CLASS
 
The base() can be used for chaining constructors in a inheritance hierarchy.
 
Destructors
 
A destructor is a special member that can be added to a class. Destructor is called automatically when an object is being removed from memory. The destructor can be very useful because it can ensure you that all objects of a particular class terminate cleanly
 
The syntax to create a destructor is very simple. The destructor name will always same as class name with tilde character (~) as prefix. No parameters are required because the destructor cannot be called manually. To add a destructor to the Rectangle class, add the following code:
 
class Rectangle
{
~ Rectangle()
{
    Console.WriteLine("Rectangle destructor executed");
}
 
Note: The destructor outputs a message only as there is no clean up required for Rectangle objects.
 
Garbage Collection(GC)
 
Garbage Collector(GC) is used for memory management in C#. When objects are created they occupy some place in your memory. As memory is a limited resource, so it is very important that once the object is no longer required, they are cleaned up and free their memory for reuse.
 
The .NET framework uses a system of garbage collection to perform this action automatically so that the developer does not need to control this directly.
 
The garbage collector periodically checks for objects in memory that are no longer in use and that are referenced by no other objects.
 
It also detects groups of objects that reference each other but as a group have no other remaining references. When detected, the objects’ destructors are executed and the memory is returned to the pool of available memory for reutilize.
 
Garbage Collection and Destructors
 
The garbage collection system is fully automated and requires little consideration by the C# developer. But, it is very important to understand that an object’s destructor is not called immediately that it is falls out of scope. There can be a delay until the garbage collector decides to reclaim the object’s memory and it is only at this point that the destructor is called.
 
 
Scroll to Top