C# Object oriented programming

C# is an object-oriented programming language, which means that it is based on the concepts of objects and classes. Object-oriented programming (OOP) is a programming paradigm that focuses on modeling real-world objects as software objects with properties and behaviors.

In C#, you define classes to represent the blueprint for objects, and you create instances of classes to represent specific objects in your code. Here's an example of a class definition in C#:

class Person

{

    public string Name { get; set; }

    public int Age { get; set; }

    

    public void SayHello()

    {

        Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");

    }

}

In this example, we define a class named Person that has two public properties, Name and Age, and a public method named SayHello that writes a message to the console.


To create an instance of the Person class, you use the new keyword and call the class constructor:

Person person = new Person();

person.Name = "John";

person.Age = 30;

person.SayHello(); // prints "Hello, my name is John and I am 30 years old."

In this example, we create an instance of the Person class and set the Name and Age properties, and then we call the SayHello method to print a message to the console.


One of the key features of OOP is inheritance, which allows you to create new classes that are based on existing classes. In C#, you can use the : operator to specify a base class for a new class. Here's an example:

class Employee : Person

{

    public int Salary { get; set; }

    

    public void GetPaid()

    {

        Console.WriteLine($"I just got paid ${Salary}!");

    }

}

In this example, we define a new class named Employee that inherits from the Person class. The Employee class has a new property named Salary and a new method named GetPaid.


When you inherit from a class, you can use all of the properties and methods of the base class in your new class, and you can also override methods or properties if you need to change their behavior.


C# also supports other OOP concepts such as polymorphism, abstraction, and encapsulation, which allow you to create more complex and flexible software systems.





Comments

Popular posts from this blog

OpenSolaris and Linux virtual memory and address space structures

Tagged architectures and multi-level UNIX

Tying top-down and bottom-up object and memory page lookups with the actual x86 page translation and segmentation