C# provides arrays and other collections for gathering into one structure groups of like-typed variables, such as string or int. A hypothetical college, for example, might track its students by using an array.

But a student defination requires much more than just a name , how should this type of program represent a student? So, in cases like this we use Classes and to access a class methods and variables we need to create it's Objects.

Defining Classes and Objects

A class is a bundling of unlike data and functions that logically belong together into one tidy package, in simple language, a class is a group of related methods and variables. A class describes these things, and in most cases, you create an instance of this class, referred to as an object. With the help of this object, you use the defined methods and variables.

Let's consider this example, suppose you want to create a Class for Vehicle.

So, we will consider this, Vehicles have Model, manufacturer, number of dorrs, number of wheels, color etc.

So C# code for above Vehicle class would be as below

public class Vehicle
{
  public string model; // Name of the model
  public string manufacturer; // Name of the manufacturer
  public int numOfDoors; // The number of doors on the vehicle
  public int numOfWheels; // You get the idea.
}

A class definition begins with the words public class, followed by the name of the class — in this case, Vehicle.

The name of the class is case sensitive. C# doesn’t enforce any rules concerning class names, but an unofficial rule holds that the name of a class starts with a capital letter.

Objects

A class object is declared in a similar (but not identical) fashion to declaring an intrinsic object such as an int. The term object is used universally to mean a “thing.” An int variable is an int object. A car is a Vehicle object. So, the following code segment creates a car of class Vehicle:

Vehicle myCar;
myCar = new Vehicle();

The first line declares a variable myCar of type Vehicle, just as you can declare a somethingOrOther of class int. (A class is a type, and all C# objects are defined as classes.) The new Vehicle() command creates a specific object of type Vehicle and stores the location in memory of that object into the variable myCar. 

The new operator creates a new block of memory in which your program can store the properties of myCar.

In C# terms, you say that myCar is an object of type Vehicle. You also say that myCar is an instance of Vehicle. In this context, instance means “an example of” or “one of.” You can also use the word instance as a verb, as in instantiating myCar.

Complete Example of using C# Classes and objects using Visual Studio Console app

Let's create a console app and see the complete example of using C# classes & objects(I hope you have already downloaded Visual Studio community 2015 or later, if not please download Visual studio first)

Step 1: You can create console app by navigating to File-> New -> Project -> Select "Visual C#"(left pane) & "Console app"(Right pane) -> Provide project name and Click "OK"

creating-console-app-visual-studio-min.png

Step 2: Now we need to create Class in our Visual Studio solution, so open "Solution explorer" in Visual Studio, on the right hand side, right-click on your Project name(ClassesAndObjects here) -> Select "Add" -> Select "Class" -> provide name to Class (Vehicle.cs) & click "OK"

create-class-in-csharp-min.png

class-csharp-add-min.png

Now, we have Created the class, let's define some variables and methods inside it to use them, go to your Vehicle.cs file and use the code below

namespace ClassesAndObjects
{
    public class Vehicle
    {
        public string model; // Name of the model
        public string manufacturer; // Ditto
        public int numOfDoors; // The number of doors on the vehicle
        public int numOfWheels; // You get the idea.
    }
}

Step 3: To use the above Created class in our console application, go to your Program.cs file and inside main method use the below C# code to create Vehicle.cs class object and save data inside it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassesAndObjects
{
    class Program
    {
        static void Main(string[] args)
        {
            // Prompt user to enter a name.
            Console.WriteLine("Enter the properties of your vehicle");
            // Create an instance of Vehicle.

            Vehicle myCar = new Vehicle();
            // Populate a data member via a temporary variable.

            Console.Write("Model name = ");
            string s = Console.ReadLine();
            myCar.model = s;

            // Or you can populate the data member directly.
            Console.Write("Manufacturer name = ");
            myCar.manufacturer = Console.ReadLine();
            // Enter the remainder of the data.
            // A temp is useful for reading ints.
            Console.Write("Number of doors = ");
            s = Console.ReadLine();
            myCar.numOfDoors = Convert.ToInt32(s);
            Console.Write("Number of wheels = ");
            s = Console.ReadLine();
            myCar.numOfWheels = Convert.ToInt32(s);
            // Now display the results.
            Console.WriteLine("\nYour vehicle is a ");
            Console.WriteLine(myCar.manufacturer + " " + myCar.model);
            Console.WriteLine("with " + myCar.numOfDoors + " doors, "
            + "riding on " + myCar.numOfWheels
            + " wheels.");
            // Wait for user to acknowledge the results.
            Console.WriteLine("Press Enter to terminate…");
            Console.Read();

        }
    }
}

As you can see in the above Code we are asking user to enter details of it's car like Model name, manufacture, number of wheels and doors, after that we are printing it, means first settings values in Vehicle class object and retrieving it using same object.

csharp-classes-and-objects-with-example-min.png

Output of the above code:

Enter the properties of your vehicle
Model name = NEXA
Manufacturer name = TATA
Number of doors = 4
Number of wheels = 4

Your vehicle is a
TATA NEXA
with 4 doors, riding on 4 wheels.
Press Enter to terminate.

C# class constructor

Before we end this article, i would like to introduce C# Constructors, Constructors are special methods, used when instantiating a class. A constructor can never return anything, which is why you don't have to define a return type for it.

A normal method is defined like this:

public string MethodName()

A constructor can be defined like this:

public Vehicle()

as you can see in the above C# code, Contructor have same name as Class and also it doesn't have any return type defined.

Contructor for our above used vehicle class can be as below, in which we are getting Model name and saving it.

public class Vehicle
    {
        public string model; // Name of the model
        public string manufacturer; // Ditto
        public int numOfDoors; // The number of doors on the vehicle
        public int numOfWheels; // You get the idea.

        public Vehicle(string model)
        {
            this.model = model;
        }
    }

Now, we would need to create class object as below

 Vehicle myCar = new Vehicle("Tata");

Where "Tata" is set as model name now.

A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new.

Unless the class is static, classes without constructors are given a public default constructor by the C# compiler in order to enable class instantiation.

You may also like to read:

C# String

C# Datetime

C# Inheritance

C# Methods

C# Method Overloading

C# Method Overriding

Abstract Class in C#