C# Object and classes

tutorial and example
tutorial and example

As we know, C# is an object oriented programming language, it provides oops concepts which are relevant to real world problems.

C# Object:

An object is a real world entity. It can be anything that exists in the real world and that has state and behavior for eg. Car, pen, chair, etc.

In C#, object is a real time entity. It is an instance of the class which can access all the fields and methods of the class.

Let’s see an example of creating object of a class using new keyword.

Student s=new student(); // creating object of student class

Example illustrates the creation of object of student class. s is the reference variable to the object for which the memory is provided at runtime by new keyword.

C# Class:

In C#, class is the group of similar type of objects. A class can have static and non static methods. It can have fields and constructors. It represents the template of its object.

C# Object and class Example:

Let’s see an example of class and object. The employee class has two fields named as id and name. the fields are initialized through object emp created in main method which is in same class.

Output

C# Class and object Example: Accessing class data from another class

We can also create object of the class in another class but the class fields and methods must be public.

Output

C# Example: printing the class variables through method

Output

C# classes and objects Example : Initializing class data by a method

Till now, we were initializing class fields in the main method. We can also create a method to initialize class data as shown below.

Output

C# Class and objects Examples: Storing and Retrieving information of various students

In the following Example, We are storing the student’s information through method and retrieving it.

Output: