Introduction:
In the previous articles, we covered the fundamentals of C#, including data types, variables, operators, control structures, and arrays and collections. Now, we will dive into the world of Object-Oriented Programming (OOP) with C#. In this article, we'll explore the concepts of classes, objects, and inheritance. In the next post, we will discuss interfaces, delegates, and events.
Classes and Objects:
A class is a blueprint for creating objects, which are instances of the class. A class can contain fields, properties, methods, and events that define the state and behavior of objects created from the class.
To define a class, use the class keyword followed by the name of the class:
class Person { // Fields, properties, methods, and events go here }
To create an object (an instance of a class), use the new keyword followed by the class name and parentheses:
Person person1 = new Person();
Inheritance:
Inheritance is a fundamental concept in OOP that allows one class to inherit the properties and methods of another class, promoting code reusability and modularity. The class that inherits from another class is called the derived class, while the class being inherited from is called the base class.
To create a derived class, use the : symbol followed by the base class name:
class Employee : Person { // Additional fields, properties, methods, and events specific to Employee }
The derived class can access all non-private members (fields, properties, methods, and events) of the base class, and can also add or override members as needed.
Example:
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."); } } class Employee : Person { public string JobTitle { get; set; } public void SayHello() { base.SayHello(); // Call the SayHello method from the base class Console.WriteLine("I work as a " + JobTitle + "."); } } // Usage Employee employee = new Employee { Name = "John", Age = 30, JobTitle = "Software Engineer" }; employee.SayHello();
Conclusion:
In this article, we introduced the concept of Object-Oriented Programming in C# by discussing classes, objects, and inheritance. These are essential concepts to understand when building applications using C#. In the next article, we will explore more advanced OOP topics such as interfaces, delegates, and events. Stay tuned for more C# learning!
Comments
Post a Comment