A class is a blueprint of an object. An object in the real world will have properties like shape, color, weight etc. Likewise, in object-oriented programming, a class defines certain properties, events, and functionalities that an object can have.
Defining a class
In C#, a class is defined by using the class keyword. Following is the general structure of a class.
access_specifier class class_name
{
//One or more Variables
access_specifier data_type variables;
//constructor
access_specifier constructor(){}
//one or more Methods
access_specifier return_type method(parameters) {}
}
- Access_specifier – Access specifiers are used to define the accessibility of the class and it’s member variables and methods. private, public, protected and internal are the access specifiers in C#. We’ll learn about them later.
- data_type – The datatype indicates the type of data stored in the variable.
- constructor – The constructor is a special member function of the class. It is called when an object is created.Constructor has the same name of the class.
Example
using System; //Adding namespaces
namespace LearnCSharp //Namespace of the class
{
class MyClass
{
//Declaring Member variables
public int length;
public int height;
public string name;
public MyClass() //Constructor
{
length = 12;
}
//A member method
public void ShowData()
{
height = 20;
Console.WriteLine(length);
Console.WriteLine(height);
Console.WriteLine(name);
Console.ReadKey();
}
}
class Program //The class
{
static void Main(string[] args) //Main method
{
MyClass cl= new MyClass(); //Creating an object
cl.name = "Rectangle"; //Setting value for a member variable of MyClass
cl.ShowData(); //Calling the member function of MyClass
}
}
}
Output
12
20
Rectangle