Object-Oriented Programming in a Nutshell

The complexity of software is ever growing, with its related issues—large codebases that may be difficult to understand and maintain. Programmers keep the complexity in check using any of a variety of programming styles, technically called programming paradigms.

To better understand this tutorial, you should know the following C# programming areas:

Object-Oriented Programming (OOP) is one such paradigm. Its approach is to have numerous basic building blocks (or units) called objects. These objects have data and functions built around them. Then objects connect with other objects using functions to form several layers of interlaced networks.

An analog of object-oriented software is a car. It is complex. However, it has several constituent parts—doors, wheels, engine, et cetera. With each piece, in turn, having simpler items—a door composes of a handle, window, outer and inner panel.

The C# language fully supports the OOP paradigm.

The “Tripod” Mechanisms of OOP

One of the core tenets of OOP aside controlling complexity is reusability. Three main mechanisms make reusability possible. They are:

  • Encapsulation
  • Inheritance
  • Polymorphism

Encapsulation

You may also refer to it as data or information hiding. Encapsulation refers to the wrapping of related properties, methods, and other members as a single unit.
This unit is isolated, and its internal details (data or information, if you will) are to be hidden.
Encapsulation protects the data from outside interference and misuse, while also providing secure connectivity through publicly available methods and properties (known as a public interface).
An analog is the headlight bulb in a car. The content (internal details) of the lamp is enclosed (encapsulation). But it maintains contact to the car through a connection (public interface).

Inheritance

It refers to the ability to use an existing class as the basis for creating a new class. In other words, it relates to the process of an object acquiring the properties of another object.

Polymorphism

In a simple word, it is the ability to use different forms (classes) interchangeably, even though the implementation of properties or methods by each class differs.

Classes and Objects

If a class is a blueprint, then a building made from the plan is an object.
A class is a template for defining or describing the type (or details) of objects. Thus, an object is a usable instance of a class.

To define a class:

class MyClass  {  }

A light version of class available in C# is the structure (struct). A structure is ideal for creating a broad range of objects without eating up a lot of memory.

To define a Struct:

struct MyStruct  {  }

Class Members

The data and functions (in general, anything defined inside) of a class are its members. The class members of a specific class may be different from those of another class.
Some class members are:

  • properties; for describing the data of a class
  • methods; for defining the behavior of a class
  • events; for providing communication between different objects and classes

Others are constructors, finalizers, operators et cetera. Properties and Fields

Properties and Fields

A field stores the actual data, while a property exposes a field. To access a field, properties use “get” and “set” procedures. These procedures offer more control over retrieving (return) or storing (set) values.
Together, fields and properties represent the information an object contains.

To define a field:

class myClass
 {
 public string MyField;
 }

To establish a property:

class MyClass
 {
 private int _sampleproperty;
 public int SampleProperty
 {
 // Return the value stored in a field. 
 get { return _sampleproperty; }
 // Store the value in the field.
 set { _sampleproperty = value; }
 }
 }

In C#, you may choose to:

  • directly create a private field where you’d store the value of the property, or
  • use an auto-implemented property that automatically
    • creates a field anonymously, and
    • stipulates the basic logic for property procedures

To define an auto-implemented property:

class MyClass  {      public int MyProperty { get; set; }  }

In C#, you also can perform additional operations for reading or writing values.

To do so:

  • define a field where you’d store the value, and
  • stipulate the basic logic for reading or writing the value

Furthermore, while most properties would have both get and set procedures; you could create properties that are read-only (can only use the get procedure, as such cannot be modified) or write-only (can only use the set procedure, as such cannot be read).

However, this ability to restrict procedures does not extend to auto-implemented properties.

Methods

Any action that an object can perform is a method.

To define a method of a class:

 class SampleClass
 {
 public int myMethod(string sampleParam)
 {
 //Returns an Integer
 return 1;
 }
 }

A class can have multiple implementations, also called overloads, of one method. These overloads would typically differ in the number or types of parameters.

To overload a method:

class MyClass
 {
 public int MyMethod(string MyParam)
 {
 // Return an Integer
 return 1;
 }
 public int MyMethod(int MyParam)
 {
 // Return an Integer
 return 2;
 }
 }

Usually, you would have to declare a method within the definition of a class. However, C# provides support for extension methods, which offer the ability to add methods to an existing class outside the actual definition of the class.

Constructors

A constructor is a type of method. It has the peculiar characteristic of being executed automatically following the creation of a certain kind of object. It will only run once after the creation of a class.

Typically, constructors initialize the data members of a new object. The constructor code is always the first to run in a class.

Like for any other method type, you can create multiple implementations or overloads of a constructor.

To define a constructor for a class:

public class MyClass
{
public MyClass()
{
// code goes here 
}
}
Finalizers

A finalizer is used to destruct an object (an instance of a class).
The garbage collector of a runtime like the .NET Framework automatically manages the release (and allocation) of memory for managed objects in your application. When it identifies an object as eligible for finalization, it invokes the finalizer automatically.

However, you may need finalizers for unmanaged resources created by your application.
A class may have only one finalizer.

Events

Events make communication between classes and objects possible. When something of interest occurs, a class or object receives notification (from another class or object) through an event.
The class(es) that receive(s) or handle(s) the event is(are) called (a) subscriber(s). While the class that sends or raises the event is called a publisher.

  • Use the event keyword to declare an event in a class.
  • Invoke the event delegate to raise an event.
  • Use the += operator to subscribe to an event or the -= operator to unsubscribe from an event
Nested Classes

Hypothetically, if a class ‘A’ is defined within another class—class ‘B’; class A is a nested class, while class B is a container class. A nested class is private by default.

To create a nested Class:

class myClass
{
class myNested
{
// code goes here 
}
}

To create a nested class instance, use the container class name followed, without space, by a dot; and followed, again without space, by the nested class name.

myClass.myNestednestedInstance = new myClass.myNested()

Access Modifiers and Access Levels

A class or class member uses an access modifier to specify the access level it provides.

In C#, the access modifiers in the table below are available:

Modifier Definition
private Type or member ONLY accessible by code in the same class
protected Type or member ONLY accessible by code in the same or derived class
internal Type or member ONLY available by code in the same assembly
protected internal Type or member ONLY accessible by code in the same assembly or by a derived class in a different assembly
public Type or member accessible by any other code in the same or different assembly

Instantiating Classes

Recall that an object is an instance of a class. Thus, the process of creating an object (or an instance) is instantiation.

To put it technically, you create an object by instantiating a class, or in other words, by creating a class instance.

MyClass myObject = new MyClass();

Following the instantiation of a class, you may assign values to the fields and procedures of the instance. You may also invoke class methods.

 // Set a property value. 
 myObject.MyProperty = "Sample String"; 
 // Call a method. 
 myObject.MyMethod();

Assign values to properties using object initializers.

 // Set a property value. 
 MyClass MyObject = new myClass
 { PropertyA = "A", PropertyB = "B" };

Static Classes and Members

A static member of a class is a field, procedure, or property shared by all class instances.

To define a static class:

 static class MyClass
 {
 public static string MyString = "My String";
 }

To access a static member, use the class name without creating an object.

Console.WriteLine(MyClass.MyString);

In C#, a static class ONLY consists of static members. A static class cannot be instantiated. A static member cannot access non-static fields, properties, or methods.

Anonymous Types

Anonymous types are a feature that enables you to create objects without having first to define the data type explicitly. Instead, the compiler auto-generates a class for you.

The class would have no suitable name (hence anonymous), but it’d contain properties specified by you in declaring the object.

To create an instance of an anonymous type:

var myObject = new { PropertyA = "A", PropertyB = "B" };

Inheritance

The inheritance concept gives you the ability to create a new class that reuses, extends, or modifies behavior defined in another class.

Hypothetically, if class ‘A’ inherits members from class ‘B’; class A is the derived class, while class B is the base class.
Note that C# does not support the concept of multiple inheritances. A derived class may only have one base class.

To inherit from a base class:

class DerivedClass:BaseClass{}

In C#, inheriting all classes is possible by default. However, you may want to restrict a specific class NOT to be used as a base class (using the sealed modifier), or to ONLY be used as a base class (using the abstract modifier).

To specify that a class cannot be used as a base class:

public sealed class A { }

To determine that a class can be used as a base class only and cannot be instantiated:

public abstract class B { }

Overriding Members

Members inherited by a derived class are by default identical (same) to the members of the base class. However, you can change the behavior of an inherited member of a derived class, by overriding it.

You could use some modifiers to define a new implementation of a property, method, or event (members) of a derived class. The table below lists these modifiers and their definitions.

Modifier Definition
virtual Permits overriding of a class member in a derived class
override Overrides a virtual (overridable) member with a base class definition
abstract Mandates that a class member you intend to override is in the derived class
new Modifier Hides an inherited member

Interfaces

An interface is similar to a class, in that it defines a set of methods, properties, and events. However, unlike a class, an interface does not provide

An interface is similar to a class, in that it defines a set of methods, properties, and events. However, unlike a class, an interface does not provide an implementation. Instead, a class implements an interface.
As a result, interfaces are defined as separate entities from classes.
That said, a class that implements an interface MUST implement all aspects of the interface precisely as defined. In this sense, an interface signifies a contract.

To define an interface:

 interface IMyInterface
 {
 void methodA();
 }

To implement an interface in class:

  class MyClass : IMyInterface
 {
 void IMyInterface.methodA()
 {
 // Method implementation. 
 }
 }

Generics

A generic is a class, structure, interface, or method with placeholders, called type parameters, for one or more of the types they use or store.

A generic is a class, structure, interface, or method with placeholders, called type parameters, for one or more of the types they use or store.

To define a Generic:

 Public class MyGeneric<T>
 {
 public T Field;
 }

To create an instance of a Generic class:

 MyGeneric<string> MyObject = new MyGeneric<string>();
 MyObject.Field = "My string";

Delegates

A type that represents the signature of a method and can provide a reference to any method that has a compatible signature is a delegate.

In C#, you may invoke (or call) the method through its delegate. You may also pass a method as an argument to other methods using its delegate.

You may consider event handlers as methods invoked through delegates.

To create a Delegate:

public delegate void MyDelegate(string str);

To create a reference to a method that matches the signature specified by the delegate:

 class myClass
 {
 // Method that matches the myDelegate signature. 
 public static void myMethod(string message)
 {
 // code goes here
 }
 // Method that instantiates the delegate. 
 void myDelegate()
 {
 myDelegate md = myMethod;
 md("My string");
 }
 }

 

Last modified: March 8, 2019

Comments

Write a Reply or Comment

Your email address will not be published.