Content

  • Inheritance
  • Polymorphism
  • Abstraction
  • Interface
  • Enum
  • Files
  • Exceptions - Try..Catch

Inheritance

In C#, it is possible to inherit fields and methods from one class to another. We group the "inheritance concept" into two categories:

  • Derived Class (child) - the class that inherits from another class
  • Base Class (parent) - the class being inherited from

To inherit from a class, use the : symbol.

If you don't want other classes to inherit from a class, use the sealed keyword

Example :

//Vehicle.cs
using System;

namespace MyApplication
{
    class Vehicle  // Base class
    {
    public string brand = "Ford";  // Vehicle field
    public void honk()             // Vehicle method 
    {
        Console.WriteLine("Welcome");
    }
    }
}

//Car.cs
using System;

namespace MyApplication
{
  class Car : Vehicle  // Derived class
  {
    public string modelName = "Mustang";  // Car field
  }
}

//Program.cs
using System;

namespace MyApplication
{
  class Program
  { 
    static void Main(string[] args)
    {
      // Create a myCar object
      Car myCar = new Car();

      // Call the honk() method (From the Vehicle class) on the myCar object
      myCar.honk();

      // Display the value of the brand field (from the Vehicle class) and the value of the modelName from the Car class
      Console.WriteLine(myCar.brand + " " + myCar.modelName);
    }
  }
}

//Output - Welcome Ford Mustang

//Sealed Class
sealed class Vehicle 
{
  ...
}

         

Polymorphism

Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.

Inheritance lets us inherit fields and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.

C# provides an option to override the base class method, by adding the virtual keyword to the method inside the base class, and by using the override keyword for each derived class methods

Example

using System;

namespace MyApplication
{
  class Animal  // Base class (parent) 
  {
    public virtual void animalSound()
    {
      Console.WriteLine("The animal makes a sound");
    }
  }

  class Pig : Animal  // Derived class (child) 
  {
    public override void animalSound()
    {
      Console.WriteLine("The pig says: wee wee");
    }
  }

  class Dog : Animal  // Derived class (child) 
  {
    public override void animalSound()
    {
      Console.WriteLine("The dog says: bow wow");
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      Animal myAnimal = new Animal();  // Create a Animal object
      Animal myPig = new Pig();  // Create a Pig object
      Animal myDog = new Dog();  // Create a Dog object
      
      myAnimal.animalSound();
      myPig.animalSound();
      myDog.animalSound();
    }
  }
}

Abstraction

Data abstraction is the process of hiding certain details and showing only essential information to the user. Abstraction can be achieved with either abstract classes or interfaces

  • Abstract Class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
  • Abstract Method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived class (inherited from).

Example

  using System;

    namespace MyApplication
    {
      // Abstract class
      abstract class Animal
      {
        // Abstract method (does not have a body)
        public abstract void animalSound();
        // Regular method
        public void sleep()
        {
          Console.WriteLine("Zzz");
        }
      }
      
      // Derived class (inherit from Animal)
      class Pig : Animal
      {
        public override void animalSound()
        {
          // The body of animalSound() is provided here
          Console.WriteLine("The pig says: wee wee");
        }
      }
    
      class Program
      {
        static void Main(string[] args)
        {
          Pig myPig = new Pig();  // Create a Pig object
          myPig.animalSound();
          myPig.sleep();
        }
      }
    }

Interface

An interface is a completely "abstract class", which can only contain abstract methods and properties (with empty bodies)

  • Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an "IAnimal" object in the Program class)
  • Interface methods do not have a body
  • On implementation of an interface, you must override all of its methods
  • Interfaces can contain properties and methods, but not fields/variables
  • Interface members are by default abstract and public
  • An interface cannot contain a constructor (as it cannot be used to create objects)
using System;

namespace MyApplication
{
    // Interface
          interface IAnimal 
    {
    void animalSound(); // interface method (does not have a body)
    }
        
    // Pig "implements" the IAnimal interface
    class Pig : IAnimal 
    {
    public void animalSound() 
    {
        // The body of animalSound() is provided here
        Console.WriteLine("The pig says: wee wee");
    }
    }
        
    class Program 
    {
    static void Main(string[] args) 
    {
        Pig myPig = new Pig();  // Create a Pig object
        myPig.animalSound();
    }
    }
}

Enum

An enum is a special "class" that represents a group of constants (unchangeable/read-only variables).

To create an enum, use the enum keyword (instead of class or interface), and separate the enum items with a comma

Example

using System;

namespace MyApplication
{
    enum Level
    {
    Low,
    Medium,
    High
    }
    class Program
    {
    static void Main(string[] args)
    {
        Level myVar = Level.Medium;
        Console.WriteLine(myVar);
    }
    }
}

Files

The File class from the System.IO namespace, allows us to work with files

The File class has many useful methods for creating and getting information about files. For example

Method Description
AppendText() Appends text at the end of an existing file
Copy() Copies a file
Create() Creates or overwrites a file
Delete() Deletes a file
Exists() Tests whether the file exists
ReadAllText() Reads the contents of a file
Replace() Replaces the contents of a file with the contents of another file
WriteAllText() Creates a new file and writes the contents to it. If the file already exists, it will be overwritten.

In the following example, we use the WriteAllText() method to create a file named "filename.txt" and write some content to it. Then we use the ReadAllText() method to read the contents of the file


using System;
using System.IO;  // include the System.IO namespace

namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      string writeText = "Hello World!";  // Create a text string
      File.WriteAllText("filename.txt", writeText);  // Create a file and write the contents of writeText to it

      string readText = File.ReadAllText("filename.txt"); // Read the contents of the file
      Console.WriteLine(readText); // Output the content
    }
  }
}

Exceptions - Try..Catch

When an error occurs, C# will normally stop and generate an error message. The technical term for this is: C# will throw an exception (throw an error).

  • The try statement allows you to define a block of code to be tested for errors while it is being executed.
  • The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

Example

using System;

    namespace MyApplication
    {
      class Program
      {
        static void Main(string[] args)
        {
          try
          {
            int[] myNumbers = {1, 2, 3};
            Console.WriteLine(myNumbers[10]);
          }
          catch (Exception e)
          {
            Console.WriteLine(e.Message);
          }    
        }
      }
    }

//Output - Index was outside the bounds of the array.