In this chapter you will learn:
- What is class in C#?
- How to declare class?
- How to create object of class?
Class is a template, declaration or blueprint that is used for classifying 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 class, the class keyword is used.
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.
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();
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.
//Printing value of name variable
Console.WriteLine("Your name is " + a.name);
class Program //Creating 3rd class
static void Main(string args)
print p = new print();
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.
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#.