Introduction to C# (C Sharp) Class

September 08, 2012 // In: C#
C# is Object Oriented Programming, so it use Classes and structs. So I’m going to introduce you the most important portion, classes.
A class is the most powerful type of data type and is a group of related variables, methods and events. You can create class instances or objects if the class is not declared static.
Declaring Class
Classes are declared using the class keyword

The class keyword is followed by the Access modifier (private, public, protected). Because public is used,  so anyone can create objects from this class. Class Name follows the class keyword (In this case Customer is the class name). You can give any name to your class. The remaining portion is the body of the class, where properties, methods and events can be defined and that are collectively referred to as class member.

Creating Objects
Sometimes terms Class and Object used interchangeably, but the reality is, class and object are different. Object is an instance of a class. Object can be created using new keyword followed by class name.

In the above code, customer1 is the reference to the object of the class customer.

The above line doest not create any reference to the object, so it does not contain any data. When we write the new keyword followed by Customer(), it assigns memory to the object of the class Customer and the reference to that memory is stored in customer1.

Constructor:
Constructor is a method which has the same name as the class and its automatically called when an object is created. You cannot call constructor manually. When you need to initialize data members of fields values or want to call any method on the object creation, you put all the initialization  in the constructor.
here is the example…

Here is the complete example

Demo: 

Hope you learned something from here… 🙂

Format Numbers to Fix Length in C#
Display Serial Number in RDLC Reports