Class - C# Basic Programming

In this chapter you will learn:
  • What is class in C#?
  • How to declare class?
  • How to create object of class?

The class is a template, declaration or blueprint that is used for classifying the object. It encapsulates variable members, functions, structure, properties and many more components. It is the basic building block of object-oriented programming. In order to create a class, the class keyword is used.

Syntax

class print
  {
 
  }

 

After creating class, you can use it by creating its object. An object is created using new keyword. Suppose you created a class print that contain following method.

class print
  {
    public void printname()
     {
       Console.WriteLine("My name is Steven Clark");
     }
  }

To use the members of class, you need to create object of this class. After creating the object of print class, you can use its members using the object name as follow:

print pr = new print();
pr.printname();

Programming Example

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

namespace Creating_Class
{
    class accept //Creating 1st. class
    {
        public string name;
        public void acceptdetails()
        {
            Console.Write("Enter your name:\t");
            name = Console.ReadLine();
        }
    }

    class print // Creating 2nd class
    {
        public void printdetails()
        {
            //Creating object of 1st. class
            accept a = new accept();
            //executing method of 1st class.
            a.acceptdetails();
            //Printing value of name variable
            Console.WriteLine("e;Your name is "e; + a.name);
        }
    }
    class Program //Creating 3rd class
    {
        static void Main(string[] args)
        {
            print p = new print();
            p.printdetails();
            Console.ReadLine();
        }
    }
}

Output

Enter your name:          Steven Clark
Your name is Steven Clark __

Guideline while creating class

  • The class name should be noun and meaningful.
  • Use either pascal case or camel case. In camel case, the first letter is small. Ex. camelCase. In pascal case first letter is capital. Ex. PascalCase. It is strictly recommended you to use pascal case for class name and camel case for variable name.
  • Your class name should not contain any special character except underscore (_) or digit. Must start your class name with character.
  • Don’t use reserved keyword for class name.

Summary

In this chapter you learned about what is class in C# and how to use it in program. In next chapter you will learn how to declare method in C#.

 

Share your thought