Void Keyword In C#

All terms are distinctive within the expansive realm of programming languages, impacting the way functions are presented both visually and logically. For instance, the "void" term serves as a cornerstone in the core principles of C#, enabling the definition of methods without necessitating a return value. It is crucial to maintain a focus on concise, clear, and effective code without unnecessary embellishment.

The void keyword is employed to indicate to the compiler and fellow developers that the function or method is designed to execute a series of instructions or processes in a specific order without the expectation of producing a return value. Even though the void keyword may seem straightforward, it holds importance in terms of comprehension and structuring code.

For programmers using C#, the keyword "void" holds significant importance. It indicates a deliberate choice to disregard return values and concentrate solely on the task at hand when defining a method. This concise syntax effectively encapsulates the straightforward nature of the void keyword, making it easy to grasp and implement.

The upcoming section will focus on real-world scenarios, providing a deeper insight into this particular term. Void serves as the keyword enabling software developers to create straightforward and more efficient solutions suitable for both beginners and advanced users. Nevertheless, like various other programming tools, the void keyword comes with its intricacies. While it enhances code clarity and readability, it also imposes several limitations.

Whether you are experienced in C# or just starting out in C# programming, understanding the significance of void keywords is essential. Let's embark on a journey to explore the capabilities and power of this fascinating feature. Following this exploration, we will uncover the path forward in C# development.

In this article, we will delve into the syntax, provide an example with a detailed explanation, and explore the advantages and disadvantages of the void keyword.

Syntax:

In C#, the void keyword features a straightforward syntax, crucial for defining functions or methods where no return values are expected. It is essential to consider both the syntax and implications of the code when aiming to create clear and functional code.

Declaring a method or function using the void keyword follows this syntax:

Example

public void MethodName(parameters)
{
    // Method implementation
}

Let us dissect this syntax:

  • Public: Visibility of the method is insured by this access controller. In this case, if this method is required from any other class, it can just be called 'public' .
  • Void: The string k beyond it designates the method's result type. "void" is the way to inform the fact that there is no function return value.
  • MethodName: The developer decides to name the method in this manner in order that it represents what the method performs in comparison to others.
  • (parameters): The method would accept the parameters. If it does accept it, then these are the only values. One comes after the other with optional arguments in parentheses. There are procedures by which the method can acquire input data, which it can then use to get its execution done.
  • {}: The braces of costly type close off the scope of the method and encapsulate the block of codes that is the way the method is being implemented.
  • Example 1: Bank Account Management System

    Example
    
    using System;
    class BankAccount
    {
        private string accountHolder;
        private double balance;
     
        public BankAccount(string accountHolder, double initialBalance)
        {
            this.accountHolder = accountHolder;
            this.balance = initialBalance;
        }
     
        public void Deposit(double amount)
        {
            balance += amount;
            Console.WriteLine($"Deposited ${amount}. Current balance: ${balance}");
        }
     
        public void Withdraw(double amount)
        {
            if (amount <= balance)
            {
                balance -= amount;
                Console.WriteLine($"Withdrawn ${amount}. Current balance: ${balance}");
            }
            else
            {
                Console.WriteLine("Insufficient funds.");
            }
        }
     
        public void DisplayBalance()
        {
            Console.WriteLine($"Account balance for {accountHolder}: ${balance}");
        }
    }
     
    class Program
    {
        static void Main(string[] args)
        {
            BankAccount account = new BankAccount("John Doe", 1000);
     
            account.DisplayBalance();
            account.Deposit(500);
            account.Withdraw(200);
            account.Withdraw(1500);
        }
    }
    

Output:

Output

Account balance for John Doe: $1000
Deposited $500. Current balance: $1500
Withdrawn $200. Current balance: $1300
Insufficient funds.

Explanation:

BankAccount Class:

  • The entity for a bank account is represented by it.
  • The account holder's name and balance are kept in the private fields protocol that is declared as the account holder and balance, respectively.
  • Using the supplied constructor method, new Balance and accountHolder fields can be initialized at the time of creation of a new BankAccount object.
  • Draws only the Deposit, Withdraw, and DisplayBalance void methods.

Deposit Process:

  • Updates the specified sum in the account balance.
  • Displays a notification with the new balance and the deposited amount.

Withdraw Method:

  • To make sure that the amount of withdrawal is either the same as the amount within the account or less than that.
  • If the money available in the account is sufficient, the withdrawal amount is debited out, and a notice with the updated balance and the withdrawal amount is printed.
  • The message is printed if the account balance is not sufficient, "Insufficient funds" .

PrintBalance Function:

The method will display the name of the account holder along with the current balance.

Program Class:

  • Creates a new instance of the BankAccount class named account for the individual named "John Doe" with an initial balance of $1000.

Main Method:

  • In the main method, the dev calls the object of the account, DisplayBalance, to call the starting balance.
  • $500 is deposited using the Deposit method, and the updated balance is on display.
  • Makes two calls, the first for $200 and the second for $1,500, to the Withdraw method.
  • The official approval of the initial withdrawal and the updated balance is $1300.
  • The error message "Insufficient funds." appears when the second withdrawal is tried again, but it doesn't work.
  • Example 2: Employee Management System

    Example
    
    using System;
    using System.Collections.Generic;
    class Employee
    {
        public string Name { get; set; }
        public string Department { get; set; }
     
        public Employee(string name, string department)
        {
            Name = name;
            Department = department;
        }
     
        public void DisplayDetails()
        {
            Console.WriteLine($"Name: {Name}, Department: {Department}");
        }
    }
     
    class Company
    {
        private List<Employee> employees;
     
        public Company()
        {
            employees = new List<Employee>();
        }
     
        public void AddEmployee(Employee employee)
        {
            employees.Add(employee);
        }
     
        public void DisplayEmployees()
        {
            for each (var employee in employees)
            {
                employee.DisplayDetails();
            }
        }
    }
     
    class Program
    {
        static void Main(string[] args)
        {
            Company company = new Company();
     
            Employee emp1 = new Employee("John", "HR");
            Employee emp2 = new Employee("Alice", "Finance");
     
            company.AddEmployee(emp1);
            company.AddEmployee(emp2);
     
            company.DisplayEmployees();
        }
    }
    

Output:

Output

Name: John, Department: HR
Name: Alice, Department: Finance

Explanation:

Employee Class:

  • It is a staff grouping.
  • The employee's name and department are stored as their values in their Name and Department properties, respectively.
  • Includes a constructor method which, during the creation of a new Employee object, initializes the properties Department and Name
  • Shows that the null method Returns the employee's name and his department by selecting DisplayDetails.

Company Class:

  • Symbolizes a business entity.
  • It uses a private member of type List<Employee> named employees to keep a group of staff.
  • Involves a constructor method that, upon creation of the new Company object, initializes the employee's list.
  • It is the defining AddEmployee and DisplayEmployees void methods.
  • Inserts an instance of the Employee class into the employee collection if it meets the specified criteria.

The DisplayEmployees function showcases the information of each employee by invoking the DisplayDetails method during each iteration over the list of employees.

Program Class:

  • Incorporates the cold outreach approach known as the warm entry point strategy.
  • Generates a fresh instance.

Main Method:

  • Creates two new Employee objects, emp1 and emp2, with departments "HR" and "Finance" and the names "John" and "Alice, "respectively.
  • Creates two new employees, emp1 and emp2, and adds them to the employee list of the firm through its AddEmployee method invocation.
  • The firm object is called to view all the employees.
  • Pros and Cons of Void Keyword in C#:

    Pros:

  • Clarity and Intention: The indication that the methods do not take part in the execution operation but do not affect the value return is made obvious from the void methods. This specificity aims at achieving code legibility and helps other programmers understand the method's purpose.
  • Simpleness: The design of void methods in such a way so that only one thing is being done and eliminating the requirement of handling back values allows for straightforward programming. Therefore, it becomes streamlined, more compact, and easier to manage.
  • Efficiency: Void methods don't know the overheads of returning values. So, they provide better performance advantages over methods that do return values. For performance-critical applications, void methods are much better as the values don't need to be assigned or managed.
  • Flexible Usage: There are a lot of occasions where the result isn't the main goal but rather the process of executing an action, like in the event handlers, utility functions, or helper methods, null methods can be applied. The adaptability of way methods makes them a fundamental technique in a programmer's toolbox.
  • Cons:

  • Restricted Usability: Blank methods can execute methods and return "null" . This limitation might become ineffective when using the method's output in processing or using it by other parts of the code. Consequently, the flexibility of the code may go down, and the function may need to be corrected to get the intended behavior.
  • Code Duplication: If this code generation does not yield the same results or needs to be repeated without having the capability to produce results, void methods may be one of the factors leading to code duplication. This might result in excessive code segments that increase the probability of a bug or a slip-up, and the codebase would be significantly harder to maintain.
  • Testing Complexity: Testing the void methods, however, may be more complicated than testing those which return a value. In most instances, a void method is known to lead to side effects, so testing them simply involves confirming the effects against the correct results rather than just picking up the return values. It may complicate the process of unit testing and may imply the need for more setup or other dependency mocking.
  • Error Handling: Void methods can hardly manage errors, especially when it happens in the process of the method being executed. It also gets complicated to handle and pass on errors inside void methods, which don't offer the possibility to return error codes or exceptions. It will lead to non-handled exceptions or inconsistent error handling within the whole code.
  • Conclusion:

In summary, within C#, the "void" term plays a crucial role in introducing a method, indicating that the method produces a result without returning any value. The significance of void methods in C# programming is apparent, with their ability to enhance code clarity, simplicity, encapsulation, efficiency, side-effect management, and usability flexibility being well-demonstrated.

The void keyword comes with a wealth of features by default, yet it also presents certain drawbacks. These drawbacks encompass diminished usability, the potential for redundant code, intricate testing procedures, challenges with error management, and difficulties in handling side effects. When incorporating void methods into their codebase, developers should carefully weigh these disadvantages to ensure informed decision-making and mitigate any potential problems.

However, the void keyword remains an essential asset in a developer's arsenal, enabling them to define functions that perform tasks without producing any output. The primary objective should always be to write code that is clear and comprehensible. Whether you are a novice or an expert in C#, understanding how to effectively utilize the void keyword is crucial. By honing their skills in C# programming, developers leverage the void keyword to construct reliable systems that can be effortlessly explained to end-users after careful consideration of its benefits and drawbacks.

Input Required

This code uses input(). Please provide values below: