Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
C# Classes
2.1.
Creating a Class
2.2.
Components of a Class
3.
C# Objects
3.1.
Creating Objects
3.2.
Components of an object
4.
Example of Class and Object
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

C# Classes and Objects

Author ANKIT KUMAR
2 upvotes
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

You might have heard several times that C# is an object-oriented programming language. One of the important words here is "object."In C#, an Object is a real-world entity. Objects are always associated with a class. A Class is like an object constructor or a "blueprint" for creating objects. Class is a group of similar objects. It can have fields, methods, constructors, etc.

Students are generally confused about what classes and objects are. Once you start learning C# and observe the code, you will be able to understand both terms in detail.

Consider banking software. Some of the attributes or states that each bank will have is:

  • Name 
  • IFSC code
  • Email
  • Phone
  • Address

There can be many other attributes also but let us restrict ourselves to the above attributes only. When we say that each bank will have the above attributes, we mean that each bank will have the above properties regardless of its size of capital. 

Apart from the above attributes, each bank will also have certain functions or behaviours like:

  • Giving loan
  • Opening a new bank account
  • Depositing money
  • Providing money withdrawal facility

Again there can be numerous other functions too that a bank can perform. But let us consider only the above attributes and functions for the time being.

This collection of attributes (or state) and functions( or behaviours) is known as a class. We can clearly see that here, "bank" is a class that has a prototype. Each bank like SBI, HDFC, AXIS must have similar features (attributes and behaviours).

Here SBI, HDFC, AXIS are objects. They have a copy of the original blueprint. But they are independent of each other.

Even now if you are confused with classes and objects, then it is completely normal. We shall see the code implementation and examples which will make the concept crystal clear.

Recommended Topic, Palindrome in C# and Ienumerable vs Iqueryable.

C# Classes

A Class is like an object constructor or a "blueprint" for creating objects. Class is a group of similar objects. It can have fields, methods, constructors, etc. A class in C# is created by using the keyword "class."

Creating a Class

Syntax:

<Modifier> class className{
    
    // data members
    
    // functions
}

Example: 

 using System;
 class CodingNinjas{
    
    //data member (attribute)
    string course1 ="C#";
    
    // methods or functions (behaviour)
    public static void Main(){
                Console.WriteLine(“DSA”);
    }
}

Output: 

DSA

Explanation:

  • We created a class named CodingNInjas using the class keyword.
  • public represents the modifier for the class.
  • A class contains data members (often called variables) and methods( or functions).

Components of a Class

The various components of a class are:

  1. Identifier: Identifier is simply the name of the class. In the above example, the name of the class is CodingNinjas. By convention, the first character of the name of the class is in capital letters.
  2. Modifier: Modifiers are used to specify the scope of accessibility of the class. The various types of modifiers are public, private, protected, internal, protected internal, private protected.
  3. Keyword class: To create a class the keyword "class" is used. For example, class CodingNinjas.
  4. Body: The body of the class contains all the attributes and behaviours of that class. The class is surrounded by curly braces {}.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

C# Objects

An object is also known as an instance of the class. All the instances or the objects share the attributes and the behaviour of the class. Every instance will have its own copy of the attributes and behaviour of the class.

Syntax:

className object_name = new className();

Example:

CodingNinjas cn= new CodingNinjas();

The above code will create object cn of the class CodingNinjas.

Creating Objects

Creating an object involves two processes:

  1. Declaring an object: The object is declared using the class name followed by the object name. Until the object is initialised it has value as null. Declaring the object will let the compiler know that it has to reserve some memory for this object.
  2. Initialising the object: The initialisation of the object is done with the help of the new keyword. The new operator is used to instantiate a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor.

Let us see how we create an object using code implementation.

 using System;
 class CodingNinjas{
    
    //data member (attribute)
    string course1 ="C#";
    
    /* a method that takes string as a parameter and 
     prints it.
    */
    public void studentName(string name){
        Console.WriteLine(name);
    }
    
   //Main method
    public static void Main(){
    /* cn_object is an object of CodingNinjas class.
    It is created with the help of the new keyword.
    */
    CodingNinjas cn_object = new CodingNinjas();
    
    // display course1 with the help of the object
    Console.WriteLine(cn_object.course1);
    
    //use the object to call the studentName() function
    cn_object.studentName("Ram");
    }
}

Output: 

C#
Ram

Components of an object

The components of an object are:

  1. State: The state is represented by the attributes of an object. For every object, it will have a copy of the data members of the class, which are known as the attributes.
  2. Behaviour: The behaviour is represented by the methods or functions of an object.
  3. Identity: Identity refers to the unique name given to an object.

Example of Class and Object

Now that we have learned about classes and objects, it is time to see some code implementation of classes and objects.

 using System;
 public class College{
    
    // data members or fields or attributes
    string name;
    string address;
    int rank;
    
    // constructor to intialise the data members
    public College(string name, string address, int rank){
        this.name=name;
        this.address= address;
        this.rank= rank;
    }
    
    // this method returns name of the college
    public string getName(){
        return name;
    }
    
    // this method returns address of the college
    public string getAddress(){
        return address;
    }
    
    // this method returns rank of the college
    public int getRank(){
        return rank;
    }
    
    public static void Main(){
        
        // object college1 is created using the new keyword
        College college1= new College("IIT", "Bombay", 1);
        
        // corresponding values are stored after function call using object
        string collegeName=college1.getName();
        string collegeAddress= college1.getAddress();
        int collegeRank= college1.getRank();
        
        //finally print the results
        Console.WriteLine("College name: {0}", collegeName);
        Console.WriteLine("College address: {0}", collegeAddress);
        Console.WriteLine("College rank: {0}", collegeRank);
        
    }
 }

Output: 

College name: IIT
College address: Bombay
College rank: 1

Explanation:

  • We created a class named College.
  • It contained various data members or variables.
  • It contained functions that returned the values of the data members.
  • It contains a constructor, which is used to initialise the data members.
  • In the Main() method, we create an object of the College class named college1.
  • Using the object college1 followed by the dot (.) operator, we are able to call the various functions that we created in our program.
  • Finally, we print the result.

 

Know What is Object in OOPs here in detail.

FAQs

1.What is a class in C#?

A Class is like an object constructor or a "blueprint" for creating objects. Class is a group of similar objects. It can have fields, methods, constructors, etc.

2. Which keyword is used to create a class in C#?

The "class" keyword is used to create a class in C#.

3. What are modifiers in C#?

Modifiers are used to specify the scope of accessibility of the class. The various types of modifiers are public, private, protected, internal, protected internal, private protected.

4. What are objects in C#?

An object is also known as an instance of the class. All the instances or the objects share the attributes and the behaviour of the class.

5. Which keyword is used to create an object in C#?

The "new" keyword is used to create an object in C#.

Key Takeaways

In this article, we have extensively discussed C# classes and objects and we also saw code implementation of the same.

  • A Class is like an object constructor or a "blueprint" for creating objects. Class is a group of similar objects.
  • An object is also known as an instance of the class. All the instances or the objects share the attributes and the behaviour of the class.
  • The creation of an object involves two processes: declaration and initialisation.

We hope that this blog has helped you enhance your knowledge regarding C# classes and objects and if you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass