Lesson 7.1

Classes and Objects in C# With Programming Example


Objective

What is classes and how to declare it?
What is objects and how to declare in?
Programming Example

What is classes and How to declare it?

A class is a collection of logic which is made by methods, variables and other data types. It is actually a blueprint of your own logic and it is used by initializing an object. A class keyword allows you to grouping related logic into a bucket and you can use this bucket by creating its object. You can better understand it by exploring following programing example.

How to declare a class?

<access specifier> class  class_name
{
//Member Variables

//Member Methods
}

What is Object?

An object is an instance of class which represents all the behavior of particular class. You can use a class at various locations and various times by creating its object. Object is the base of OOPS (Object Oriented Programming Structure).

How to declare an object?

Class_name object_name = new class_name();

Programming Example:

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

namespace class_objects
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating Object of PrintDetails
            PrintDetails pd = new PrintDetails();
            pd.print();
            Console.ReadKey();
        }
    }

    class PrintDetails
    {       
        public void print()
        {
            Console.WriteLine("Hello Friends!!!");
        }
    }
}

Output

Hello Friends!!!
__

You can better understand class and objects by exploring this programming example of classes and objects. In this program what we did:

  1. Created a class PrintDetails() that holds a function print()
  2. In the main method we created object pd for class PrintDetails()
  3. In next line we called the method print() using object pd.

Summary

In this chapter you have learned what are classes and objects in C#. In the next chapter you will learn very important topic of c# and that is creating functions or method.

BackNext