Building Console Applications with OOPs Concepts in C#

Building Console Applications with OOPs Concepts in C#

Are you ready to take your programming skills to the next level and build brilliant console applications using C#? In this blog post, we'll take you through the entire process, from installing the .NET framework to mastering essential OOPs concepts like classes, objects, inheritance, and polymorphism. Whether you're a beginner or an experienced programmer, you'll find plenty of interesting and useful information in this post. So, let's dive in and start building some amazing console applications!

Previously, in my previous blog post, I discussed how one can get started with Splashkit(a library/framework in C++). So similarly, this is going to be an interesting journey with c#.

Creating Project:

For Visual Studio:

Step 1: Open Visual Studio, and choose Create a new project in the Start window.

Step 2: Select All languages in the Create a new project box, then C# from the dropdown list. Select Windows from the All platforms menu and Console from the All project types menu.

Select the Console App template after applying the language, platform, and project type filters, and then click Next. If you don't see the Console App template, select Install more tools and features.

In the Visual Studio Installer, choose the .NET desktop development workload, and then select Modify

.Step3: Write any name for your project in this

And your new project will be created with a template, and you can start writing code in it.

For VS Code:

Step 1: Download and install dot net core for c# from here https://dotnet.microsoft.com/en-us/download

Step 2: Open terminal in VS Code, and type **"dotnet new console" ,**this will successfully create a new file where you can start writing code.

Basic Input and Output Operations in C# Console Applications In a console application:

The console window is used for input and output activities. In C#, you can use the Console class to read user input and show it on the console window. In a C# console program, you may do the following basic input and output operations:

  1. Output Displaying You may utilise the Console to display output on the console window.WriteLine() is a method. This function accepts a string as input and shows it in the console window on a new line. Here's an illustration:
Console.WriteLine("Hello, World!");

This code will display the message "Hello, World!" on a new line in the console window.

  1. Reading Data The Console may be used to read user input.The ReadLine() function reads a line of text. This function reads from the console window and returns it as a string. Here's an illustration:
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name + "!");

This code will prompt the user to enter their name, read the input from the console window, and display a personalized greeting message.

  1. Output Formatting Formatting options can be used to show output in a specified format. To show integers with a certain amount of decimal places, for example, you may use the Console.WriteLine() function with formatting settings. Here's an illustration:
double pi = 3.14159265358979323846;
Console.WriteLine("The value of pi is {0:F2}", pi);

This code will display the value of pi with two decimal places.

Handling Exceptions in C# Console Applications

Exception handling is a key topic in programming that allows you to manage problems and exceptions that may arise during program execution. To manage exceptions and avoid your program from crashing, you may use try-catch blocks in C#. Exception handling may be used in your C# console application in the following ways:

  1. Exception Handling A try-catch block may be used in your C# console program to manage exceptions. The code in the try block may throw an exception, and the code in the catch block handles the exception. Here's an illustration::
try
{
    int x = 10;
    int y = 0;
    int z = x / y;
}
catch (Exception ex)
{
    Console.WriteLine("An error occurred: " + ex.Message);
}
  1. Several Catch Blocks To handle different sorts of exceptions, you can utilise numerous catch blocks. This allows you to handle each exception differently. Here's an illustration:
try
{
    int[] numbers = { 1, 2, 3 };
    Console.WriteLine(numbers[3]);
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("An index out of range error occurred: " + ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("An error occurred: " + ex.Message);
}

The try block in this example contains code that attempts to access a member of the numbers array that is out of range, resulting in an IndexOutOfRangeException. This exception is caught by the first catch block, which displays an error message. The second catch block is responsible for catching any further exceptions and displaying a generic error message.

  1. Finally Block You can use a finally block to execute code that must be executed regardless of whether an exception is thrown or not. Here's an example:
try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Code that handles the exception
}
finally
{
    // Code that must be executed regardless of whether an exception is thrown or not
}

In this example, the finally block contains the code that must be executed regardless of whether an exception is thrown or not. This can be useful for releasing resources or closing connections.

OOPs in C# Console Applications

So, for now, we will not go into much in detail but still try to learn about object-oriented programming concepts in C#.

Object-Oriented Programming (OOP) Concepts in C# Console Applications Object-oriented programming (OOP) is a programming paradigm that is based on the concept of objects, which can contain data and code.

  1. Classes and Objects: A class is a blueprint for creating objects. It defines the properties and methods that an object of that class will have. To create a class, you can use the following syntax. Here's an example:

     class Book{
     int pages;
     string title;
     string author;
    
     public Book(int _pages,string _title,string _author){
     pages=_pages;
     title=_title;
     author=_author;
     }
    
     }
    

    Here, we have created a Book Class, which contains three states, pages, a title and an author. As we know every book will have several pages, a title and an author. So after that, a constructor is written, which means, whenever an object will be created of the Book class in the main method, this Constructor will be invoked automatically, which will initialize the number of pages, the title and the name of the author

    The Special Thing about classes is, that we can use different access modifiers, to encapsulate the behaviors and states of objects, for example, the public access modifier refers to that we can access that behavior or state in other classes too, similarly private access modifier limits the accessibility to that particular class only.

    Here is how you can create an object in the main method.

     static void Main(string[] args){
     Book harryPotter=new Book(275,"Harry Potter and the Sorcerer's Stone","J.K. Rowling");
     }
    

Inheritance: Inheritance is a mechanism that lets you construct a new class from an existing one. The new class inherits the previous class's attributes and methods and can add new ones of its own. You may use the: operator to create a new class that inherits from an existing class. Here's an illustration:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
Person person = new Person();
person.Name = "John";
person.Age = 30;
class Employee : Person
{
    public int Salary { get; set; }
}
Employee employee = new Employee();
employee.Name = "John";
employee.Age = 30;
employee.Salary = 50000;
  1. Polymorphism: Polymorphism is a mechanism that allows you to use a single interface to represent multiple types of objects. In C#, you can use polymorphism to create methods that can accept objects of different types. Here's an example:
class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("The animal makes a sound");
    }
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("The dog barks");
    }
}

class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("The cat meows");
    }
}

Animal animal1 = new Dog();
Animal animal2 = new Cat();

animal1.MakeSound();
animal2.MakeSound();

In this example, the Animal class defines a virtual method: MakeSound. The Dog and Cat classes override this method to provide their implementation. An object of the Dog class and an object of the Cat class is created and assigned to variables of the Animal type. The MakeSound method is called on each object, and the appropriate implementation is executed. However, this is just an overview of how polymorphism takes place, we would cover these all topics in detail in the next blogs.

Interfaces And Abstract Classes:

Interfaces and abstract classes are two important concepts in object-oriented programming that allow you to define common behavior for a group of related classes. In C#, you can use interfaces and abstract classes to create code that is modular, reusable, and easy to maintain. Here's how you can use interfaces and abstract classes in your C# console application:

  1. Interfaces: An interface is a contract that defines a set of methods and properties that a class must implement. An interface does not provide any implementation of its own. To implement an interface, a class must provide its own implementation of all the methods and properties defined in the interface. Here's an example:
interface IAnimal
{
    void MakeSound();
}

class Dog : IAnimal
{
    public void MakeSound()
    {
        Console.WriteLine("The dog barks");
    }
}

class Cat : IAnimal
{
    public void MakeSound()
    {
        Console.WriteLine("The cat meows");
    }
}

IAnimal animal1 = new Dog();
IAnimal animal2 = new Cat();

animal1.MakeSound();
animal2.MakeSound();

In this example, the IAnimal interface defines a single method: MakeSound. The Dog and Cat classes implement this interface by providing their own implementation of the MakeSound method. An object of the Dog class and an object of the Cat class are created and assigned to variables of the IAnimal type. The MakeSound method is called on each object, and the appropriate implementation is executed.

  1. Abstract Classes: An abstract class is a class that cannot be instantiated on its own. It provides a base implementation for a group of related classes, but it does not provide a complete implementation of its own. To use an abstract class, you must create a subclass that provides its own implementation of the abstract methods and properties defined in the abstract class. Here's an example:
abstract class Animal
{
    public abstract void MakeSound();
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("The dog barks");
    }
}

class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("The cat meows");
    }
}

Animal animal1 = new Dog();
Animal animal2 = new Cat();

animal1.MakeSound();
animal2.MakeSound();

In this example, the Animal class is an abstract class that defines a single abstract method: MakeSound. The Dog and Cat classes inherit from the Animal class and provide their own implementation of the MakeSound method. An object of the Dog class and an object of the Cat class are created and assigned to variables of the Animal type. The MakeSound method is called on each object, and the appropriate implementation is executed.

Key Takeaways:

here are the key takeaways from this blog post:

  1. C# is a powerful and versatile programming language that is widely used for building desktop, web, and mobile applications.

  2. C# console applications are a simple and effective way to test your programming skills and build useful applications.

  3. To create a C# console application, you need to install the .NET framework and use Visual Studio or VS Code to create a new project.

  4. Basic input and output operations, exception handling, and object-oriented programming (OOP) concepts like classes, objects, inheritance, polymorphism, interfaces, and abstract classes are essential for building complex and sophisticated C# console applications.

  5. By mastering these concepts, you can take your programming skills to the next level and build brilliant console applications using C#.

  6. C# console applications can perform a wide range of tasks, including data processing, file manipulation, system administration, networking, and database programming.

  7. Continuous learning is essential for staying up-to-date with the latest technologies, programming languages, and best practices in the technology and coding field.

By following these guidelines and best practices, you can create high-quality C# console applications that are efficient, reliable, and easy to maintain.

It is it for now, alot of new and intersting blogs would be posted in upcoming future, so be tuned here on hasnode.