Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

C# Classes and Objects:


Absolutely! In C#, a class is like a blueprint or a template for creating objects. Objects are instances of classes, and they represent real-world entities or concepts. Let's break it down with a simple example:

Explanation:

Example:

Let's create a simple class called Person with attributes such as Name and Age, along with a method called SayHello to demonstrate the concept:

Example

using System;

// Define the Person class
class Person
{
// Attributes (Properties)
public string Name { get; set; }
public int Age { get; set; }

// Method (Behavior)
public void SayHello()
{
Console.WriteLine($"Hello, my name is {Name} and I'm {Age} years old.");
}
}

class Program
{
static void Main(string[] args)
{
// Create an object of the Person class
Person person1 = new Person();

// Set the attributes of the person1 object
person1.Name = "Alice";
person1.Age = 30;

// Call the SayHello method on the person1 object
person1.SayHello();

// Create another object of the Person class
Person person2 = new Person();

// Set the attributes of the person2 object
person2.Name = "Bob";
person2.Age = 25;

// Call the SayHello method on the person2 object
person2.SayHello();
}
}

In this example:

When you run this program, it will output:

Example

Hello, my name is Alice and I'm 30 years old.
Hello, my name is Bob and I'm 25 years old.

This demonstrates how classes and objects work in C#. The Person class serves as a blueprint, and the person1 and person2 objects are instances of that class, each with its own set of attributes and behaviors.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java