Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C#

Learn step by step



Classes

A class is simply a representation of a type of object. It is the blueprint / plan / template that describes the details of an object. A class is the blueprint from which the individual objects are created.

For example:

Take an example of a bowl in which you can bake a cake, the cake could be of different flavours so cake is my class and its flavors are objects.


Defining Classes

Let's walk through the source code needed to create a class definition. The first line of code defines the code block as a class definition using the keyword Class followed by the name of the class. The body of the class definition is enclosed by an open and closing curly bracket. The code block is structured like this:

<access specifier> class class_name
{
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list)
{
// method body
}
<access specifier> <return type> method2(parameter_list)
{
// method body
}
...
<access specifier> <return type> methodN(parameter_list)
{
// method body
}
}

How can you create a class and object in C#

class Program
{
static void Main(string[] args)
{
baby aisha = new baby();
aisha.crawl();
Console.WriteLine("i am too little so i can crawl only :-)");
Console.ReadLine();
aisha.food();
Console.WriteLine("i eat mashed potatoes");
Console.ReadLine();
}
}

class baby
{
public void crawl()
{
}
public void food()
{
}
}
Creating Class Properties

After defining the starting and ending point of the class code block, the next step is to define the instance variables (often referred to as fields) contained in the class. These variables hold the data that an instance of your class will manipulate. The Private keyword ensures that these instance variables can be manipulated only by the code inside the class. Here are the instance variable definitions:

private int _empID;
private string _loginName;
private string _password;
private string _department;
private string _name;

When a user of the class (client code) needs to query or set the value of these instance variables, public properties are exposed to them. Inside the property block of code are a Get block and a Set block. The Get block returns the value of the private instance variable to the user of the class. This code provides a readable property. The Set block provides a write-enabled property; it passes a value sent in by the client code to the corresponding private instance variable. Here is an example of a property block:

public string Name
{
get { return _name; }
set { _name = value; }
}

There may be times when you want to restrict access to a property so that client code can read the property value but not change it. By eliminating the Set block inside the Property block, you create a read-only property. The following code shows how to make the EmployeeID property read-only:

public int EmployeeID
{
get { return _empID; }
}

Newcomers to OOP often ask why it's necessary to go through so much work to get and set properties. Couldn't you just create public instance variables that the user could read and write to directly? The answer lies in one of the fundamental tenets of OOP: data encapsulation. Data encapsulation means that the client code does not have direct access to the data. When working with the data, the client code must use clearly defined properties and methods accessed through an instance of the class. The following are some of the benefits of encapsulating the data in this way:

  • Preventing unauthorized access to the data.
  • Ensuring data integrity through error checking.
  • Creating read-only or write-only properties.
  • Isolating users of the class from changes in the implementation code.

For example, you could check to make sure the password is at least six characters long via the following code:

public string Password
{
get { return _password; }
set
{
if (value.Length >= 6)
{
_password = value;
}
else
{
throw new Exception("Password must be at least 6 characters");
}
}
}
Creating Class Methods

Class methods define the behaviors of the class. For example, the following defines a method for the Employee class that verifies employee logins:

public void Login(string loginName, string password)
{
if (loginName == "Jones" & password == "mj")
{
_empID = 1;
Department = "HR";
Name = "Mary Jones";
}
else if (loginName == "Smith" & password == "js")
{
_empID = 2;
Department = "IS";
Name = "Jerry Smith";
}
else
{
throw new Exception("Login incorrect.");
}
}

When client code calls the Login method of the class, the login name and password are passed into the method (these are called input parameters). The parameters are checked. If they match a current employee, the instance of the class is populated with attributes of the employee. If the login name and password do not match a current employee, an exception is passed back to the client code.

Using Constructors

In OOP, you use constructors to perform any processing that needs to occur when an object instance of the class becomes instantiated. For example, you could initialize properties of the object instance or establish a database connection. The class constructor method is named the same as the class. When an object instance of a class is instantiated by client code, the constructor method is executed. The following constructor is used in the Employee class to initialize the properties of an object instance of the Employee class. An employee ID is passed in to the constructor to retrieve the values from data storage, like so:

public Employee(int empID)
{
//Retrieval of data hardcoded for demo
if (empID == 1)
{
_empID = 1;
LoginName = "Smith";
Password = "js";
Department = "IT";
Name = "Jerry Smith";

}
else if (empID == 2)
{
_empID = 2;
LoginName = "Jones";
Password = "mj";
Department = "HR";
Name = "Mary Jones";
}
else
{
throw new Exception("Invalid EmployeeID");
}
}

A constructor will have exact same name as the class and it does not have any return type. Following example explains the concept of constructor:


using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line()
{
Console.WriteLine("Object is being created");
}

public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
}

static void Main(string[] args)
{
Line line = new Line();
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}

Output

Object is being created
Length of line : 6

A default constructor does not have any parameter but if you need a constructor can have parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation as shown in the following example:


using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line(double len) //Parameterized constructor
{
Console.WriteLine("Object is being created, length = {0}", len);
length = len;
}

public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
}

static void Main(string[] args)
{
Line line = new Line(10.0);
Console.WriteLine("Length of line : {0}", line.getLength());
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}

Output

Object is being created, length = 10
Length of line : 10
Length of line : 6
Destructor

.Net will clean up the un-used objects by using garbage collection process. It internally uses the destruction method to clean up the un-used objects. Some times the programmer needs to do manual cleanup.

Syntax:

~<ClassName>
{}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BRK.ConstructorExample
{
class Welcome
{
// Default constructor
public Welcome()
{
Console.WriteLine("Welcome message from Default Constructor...");
}
// Destructor
~Welcome()
{
Console.WriteLine("Destructor called");
}
}
class Program
{
static void Main(string[] args)
{
// Creating object for Welcome class
// This will called default constructor
Welcome obj = new Welcome();
Console.Read();
}
}
}

Note: Destructor will call after execution of the program.

Static Members of a C# Class

C# provides the important feature to create static classes, there are two main features of a static class, one is no object of static class can be created and another is, a static class must contain only static members, then it is important that what is the main benefit to create a static class, the main benefit of making static class, we do not need to make any instance of this class ,all members can be accessible with its own name.

Declaration:

A static class is created by using keyword 'Static' as shown here:

Static class Clasname
{
//C#
}

One more thing that is notable-within static class, all members must be explicitly specified as static, static class does not automatically make its members static. Static class can contain a collection of static methods.

using System;

static class Shape
{
public static double GetArea(double Width, double height)
{
return Width * Height;
}
}

class Ractangle
{
private void GetRactangleArea()
{
Double Area;
Area = Shape.GetArea(10, 5);
}
}

Shape is static class, it contain staic function GetArea.Ractangle is other class and with in GetArea function can be access without creating instance of Class Shape.

Although a static class cannot have an instance constructor, it can have a static constructor.

Note: Destructor will call after execution of the program.

Static Members of a C# Class

C# provides the important feature to create static classes, there are two main features of a static class, one is no object of static class can be created and another is, a static class must contain only static members, then it is important that what is the main benefit to create a static class, the main benefit of making static class, we do not need to make any instance of this class ,all members can be accessible with its own name.

Declaration:

A static class is created by using keyword 'Static' as shown here:

Static class Clasname
{
//C#
}

One more thing that is notable-within static class, all members must be explicitly specified as static, static class does not automatically make its members static. Static class can contain a collection of static methods.

using System;

static class Shape
{
public static double GetArea(double Width, double height)
{
return Width * Height;
}
}

class Ractangle
{
private void GetRactangleArea()
{
Double Area;
Area = Shape.GetArea(10, 5);
}
}

using System;
namespace StaticVarApplication
{
class StaticVar
{
public static int num;
public void count()
{
num++;
}
public static int getNum()
{
return num;
}
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s = new StaticVar();
s.count();
s.count();
s.count();
Console.WriteLine("Variable num: {0}", StaticVar.getNum());
Console.ReadKey();
}
}
}

Output

Variable num: 3


Related Videos