Classes and objects in C#

 What is a class

A class is like a container which contains methods, fields, constructors events, and delegates etc. Just like every other object oriented programming language, everything in C# is associated with a class and object. A class depicts real world entity. For example, in real world, a car has several characteristics like colour, speed, etc. Also a car has wheels, steering, seats and many other parts. you can create 'Car' class in C# containing properties like Wheel, Steering. Car class will have methods to show the functionality of the Car like Start,Stop,DoorOpen , DoorClosed, etc.

What is an object

An object is an instance of a class. Using object, we can access the properties and methods of a class. We can create multiple objects of a single class.

Declaring a class

To create a class in C#, use the keyword class followed by name of the class.

class Employee

{
}


You can create properties, methods and variables in class.

class Employee
{

    string Color="Red";
}


To create object of a class, use new keyword.

Employee emp=new Employee();

Access the variable of a class using "." operator.

Console.WriteLine(emp.Color); 


Program

 
public class Employee
{
    string name="Vishal";
}
public class Program
{
    static void main(string [] args)
    {
        Employee emp=new Employee();
        Console.WriteLine("Employee name is " + emp.name);
    }
}

Comments

Popular posts from this blog

Implicitly typed keyword - var in C#

Data types in C#