OneBite.Dev - Coding blog in a bite size

Declare An Object In C#

Code snippet for how to Declare An Object In C# with sample and detail explanation

Object-oriented programming (OOP) in C# is a fundamental concept, and declaring an object forms the basis of OOP. This article details how you can declare an object in C# with a simple and understandable example along with step by step explanation.

Code snippet to Declare an Object in C#

Here is a basic example of declaring an object in C#:

public class Person 
{
    public string name;
    public int age;
}

class Program
{
    static void Main(string[] args) 
    {
        Person person1 = new Person();
        person1.name = "John Doe";
        person1.age = 30;

        Console.WriteLine("Name: " + person1.name);
        Console.WriteLine("Age: " + person1.age);
    }
}

Code Explanation for Declaring an Object in C#

In C#, before you can create an object, you need to define a class. A class is a blueprint for the object. We’ll break down the steps you follow to create a class and thereafter an object.

Step 1: Define the Class As seen in the code snippet above, we start by declaring a Person class using the public keyword. This class has two attributes: name and age.

public class Person 
{
    public string name;
    public int age;
}

Step 2: Declare an Object of the Class Once you have a class, you can create objects of the class - in this case, Person. We declare an object person1 of the Person class using the new keyword.

Person person1 = new Person();

Step 3: Assign Values to the Object Attributes After the object person1 is declared, we can assign values to its attributes name and age.

person1.name = "John Doe";
person1.age = 30;

Step 4: Print the Object Attributes Once you have an object with its attributes set, you can use them as per your needs, like printing them on the console in our case.

Console.WriteLine("Name: " + person1.name);
Console.WriteLine("Age: " + person1.age);

Remember that in C#, an object is a standalone entity with its own identity and characteristics. It consists of state and behavior. In our Person example, name and age define the state of the object, whereas the Person class can have methods (behaviors) that act on these attributes.

c-sharp