C# Fundamentals: A Beginner's Guide to Object-Oriented Programming

C# Fundamentals: A Beginner's Guide to Object-Oriented Programming

Object-oriented programming (OOP) is a fundamental part of modern software development, and C# is a great language for learning OOP concepts. In this article, we'll take a step-by-step approach to understanding OOP in C#, from defining classes and creating objects to advanced techniques like inheritance and polymorphism.

06-01-2023 |

C#

Object-oriented programming (OOP) is a popular programming paradigm that is widely used in modern software development. It is a way of organizing code into logical units called "objects" that represent real-world entities and the actions that can be performed on them. In this article, we'll provide a beginner's guide to OOP in C#, one of the most popular programming languages for building Windows applications.

We'll start by introducing the basics of defining classes and creating objects in C#. Then, we'll delve into more advanced concepts such as inheritance, polymorphism, and encapsulation, and show you how to use these OOP techniques to design reusable and modular code.

Throughout the article, we'll provide plenty of code examples to help you understand the concepts and see how they work in practice. Whether you're new to C# or just looking to brush up on your OOP skills, this guide will give you a solid foundation in object-oriented programming.

Here are the topics that we will cover:

1. Defining Classes and Creating Objects

In C#, a class is a blueprint for creating objects. You can think of a class as a template for an object, and an object as an instance of a class.

To define a class in C#, you use the 'class' keyword, followed by the name of the class. For example:

In object-oriented programming (OOP), a class is a template that defines the attributes and behavior of a type of object. A class can have three types of members: fields, properties, and methods.

Fields are variables that belong to a class and store data. They are defined within the class, but outside of any method. Fields are usually marked as private, which means they can only be accessed within the class.

Properties Properties are like fields, but they have additional behavior. They allow you to get and set the value of a field, and they can have additional logic such as validation. Properties have a getter and a setter, which are methods that respectively return and assign a value to the property.

Methods are functions that belong to a class and perform a specific task. They are defined within the class, and can have parameters and a return type. Methods can be marked as public, which means they can be called from outside the class, or as private, which means they can only be called within the class.

Inside the class definition, you can add fields, properties, and methods that belong to the class. For example:

Once you have defined a class, you can create objects from it using the 'new' operator. For example:


2. Implementing inheritance

Inheritance is a way to create a new class that is a modified version of an existing class. The new class is called the derived class, and the existing class is the base class.

The derived class inherits all the fields and methods of the base class, and can also have additional fields and methods of its own. This allows you to create a hierarchy of classes, with more specialized classes derived from more general ones.

To create a derived class in C#, you use the `:` operator followed by the name of the base class. For example:

This creates a new class called `SportsCar` that is derived from the `Car` class. The `SportsCar` class has all the fields and methods of the `Car` class, as well as any additional fields and methods that you define in its own class definition.


3. Overriding Methods

In C#, you can override a method in a derived class to provide a different implementation than the one in the base class. This is called method overriding.

To override a method in C#, you use the `override` keyword and define a new implementation for the method in the derived class. For example:

In this example, the `Drive` method in the `SportsCar` class overrides the `Drive` method in the `Car` class. The `virtual` keyword in the base class indicates that the method can be overridden in a derived class.

You can also use the `base` keyword to call the base class's version of an overridden method from within the derived class. For example:

This can be useful if you want to reuse some of the code in the base class's implementation, but also add your own custom behavior

That's the basics of overriding methods in C#! In the next section, we'll look at polymorphism, which allows you to create a single interface for multiple types of objects.


4. Polymorphism through Interfaces and Abstract Classes

Polymorphism is a powerful technique that allows you to create a single interface for multiple types of objects. In C#, you can achieve polymorphism through interfaces and abstract classes.

An interface is a set of related methods that a class can implement. A class that implements an interface must provide an implementation for all the methods in the interface. For example:

In this example, the `ISpeak` interface has a single method called `Speak`, and the `Dog` and `Cat` classes both implement the `ISpeak` interface by providing their own implementation of the `Speak` method. Now, you can create a list of `ISpeak` objects and add both dogs and cats to it:

Then, you can loop through the list and call the `Speak` method on each object:

This will output a dog noise, followed by a cat noise, because the `Speak` method is called on the correct object and the correct implementation is used.

An abstract class is a special kind of class that cannot be instantiated on its own, but can be used as a base class for derived classes. An abstract class can have both abstract methods (methods with no implementation) and concrete methods (methods with an implementation). For example:

In this example, the `Animal` class is an abstract class with an abstract `MakeNoise` method and a concrete `Eat` method. The `Dog` and `Cat` classes both derive from the `Animal` class and provide an implementation for the `MakeNoise` method. You can use polymorphism with abstract classes in the same way as with interfaces.

In the next section, we'll look at encapsulation, which allows you to protect the data inside an object from external access or modification.


5. Access modifiers (e.g., public, private, protected) and encapsulation

In C#, you can use access modifiers to control the visibility and accessibility of class members such as fields, properties, and methods. This is known as encapsulation, and it is a key concept in object-oriented programming.

There are four access modifiers in C#:

  • public: A class member that is marked as public can be accessed from anywhere.
  • private: A class member that is marked as private can only be accessed within the class.
  • protected: A class member that is marked as protected can only be accessed within the class and its derived classes.
  • internal: A class member that is marked as internal can only be accessed within the same assembly (i.e., compiled code).

For example:

In this example, the `balance` field is marked as `private`, so it can only be accessed within the `BankAccount` class. The `Deposit`, `Withdraw`, and `GetBalance` methods are marked as `public`, so they can be accessed from anywhere.

This allows you to control the data inside the `BankAccount` object and prevent external access or modification. For example, you can prevent users from directly setting the balance field, and instead require them to use the `Deposit` and `Withdraw` methods.

Another example:

That's the basics of access modifiers and encapsulation in C#! In the next section, we'll look at how to use the `static` keyword to create class-level members.

In this example, the `Name` property is marked as `public`, so it can be accessed and modified from outside the `Student` class. The `age` field is marked as `private`, so it can only be accessed within the `Student` class, but it is also exposed through a `public` `Age` property that has a `get` and a `set` accessor.

This allows you to control the data inside the `Student` object and prevent external access or modification of the `age` field, while still allowing the `Age` property to be used to get and set the age from outside the class.

The `id` field is also marked as `private`, and it is exposed through a `public` `GetId` method that allows it to be accessed from outside the class, but not modified. This allows you to control the data inside the `Student` object and prevent external access or modification of the `id` field.


6. Constructors and destructors

In C#, a constructor is a special method that is called when an object is created. It is used to initialize the object and set its initial state. A class can have multiple constructors with different parameters, and the appropriate constructor is called based on the arguments passed when the object is created.

For example:

In this example, the `BankAccount` class has two constructors. The first constructor takes a single `string` parameter for the account number, and the second constructor takes a `string` parameter for the account number and a `decimal` parameter for the balance. The second constructor calls the first constructor using the `: this(accountNumber)` syntax, which allows you to reuse code and avoid duplicating it.

You can also define a default constructor, which is a constructor that takes no parameters. If a class does not have a defined constructor, a default constructor is automatically provided. However, if you define any constructors for a class, the default constructor is not provided automatically, and you must define it yourself if you want one.

A destructor is a special method that is called when an object is destroyed. It is used to release resources and perform cleanup tasks. A class can only have one destructor, and it is defined using the `~` symbol followed by the class name. The destructor is called automatically by the garbage collector when the object is no longer needed. However, you should not rely on destructors for critical cleanup tasks, as the garbage collector is not guaranteed to run at any specific time.

For example:

In this example, the `FileReader` class has a constructor that takes a `string` parameter for the file path and creates a `StreamReader` object to read the file. The `~FileReader` destructor is called when the `FileReader` object is destroyed, and it closes the `StreamReader` object to release the resources it is using. However, you should generally use the `using` statement to ensure that resources are properly disposed, rather than relying on destructors.


7. What's next?'

Congratulations on completing this beginner's guide to C# and object-oriented programming! You now have a solid foundation in the fundamentals of C#, and you are ready to start exploring more advanced topics.

Here are a few ideas for where to go next with your C# skills:

  • Learn about the .NET framework and how to build desktop, web, and mobile applications with C#.
  • Explore the various libraries and frameworks available for C#, such as ASP.NET, WPF, and Xamarin.
  • Dive deeper into object-oriented programming concepts, such as polymorphism, inheritance, and interfaces.
  • Learn about data structures and algorithms, and how to implement them in C#.
  • Get involved in the C# community by joining online forums, attending meetups, and participating in hackathons.

With practice and persistence, you will be able to master C# and build a wide range of applications. So don't stop here - keep learning and growing your skills, and you'll be an expert C# developer in no time!


Like what you see?


New C# Learning Area - Free!

Our website now offers a new section on C# theory, including code examples and related video tutorials.

ZetBit

Subscribe to ZetBits Newsletter