Skip to main content

New feature in .NET 4.0 : Optional parameters -- Step by Step to Advanced -- Part 1

Optional Parameters:

.NET introduced a new feature called Optional parameters in the version 4.0, where you can leave a particular parameter in the calling method and CLR will automatically assign the default value (That you need to provide prior)


Example:

Let's have a Console Application to discuss this,


    class Program
    {
        static void Main(string[] args)
        {
            MyClass myclass = new MyClass();
            myclass.MyMethod();

            Console.ReadLine();
        }
    }


    class MyClass
    {
        public void MyMethod()
        {
            Console.WriteLine("In MyMethod - No Parameters");
        }

    }



Output:

In MyMethod - No Parameters


Adding one more MyMethod with a single int parameter


        public void MyMethod(int a = 10)
        {
            Console.WriteLine("In MyMethod - Single Parameters");

        }

Then calling

            myclass.MyMethod();

What will be the output?

Obviously

In MyMethod - No Parameters


To Expand further


        static void Main(string[] args)
        {
            MyClass myclass = new MyClass();
            //myclass.MyMethod();


            myclass.MyMethod(1, 5);
            Console.ReadLine();
        }

// Adding a Overload Method


    class MyClass
    {
        public void MyMethod()
        {
            Console.WriteLine("In MyMethod - No Parameters");
        }

        public void MyMethod(int a, int b)
        {
            Console.WriteLine("a is :{0} ", a);
            Console.WriteLine("b is :{0} ", b);

            Console.WriteLine("In MyMethod - With Parameters int a, int b");
        }
    }


Output

a is :1
b is :5
In MyMethod - With Parameters int a, int b


And here comes the optional parameter:


        public void MyMethod(int a, int b = 8)
        {
            Console.WriteLine("a is :{0} ", a);
            Console.WriteLine("b is :{0} ", b);

            Console.WriteLine("In MyMethod - With Parameters int a, int b");
        }

Assigning the value in the called method will do the magic, but we still need to go further,


            MyClass myclass = new MyClass();
         
            myclass.MyMethod(1, 5);


This will not invoke the optional parameters to work, because we're passing the value in the calling method

so obviously the output will be

a is :1
b is :5
In MyMethod - With Parameters int a, int b

Ok then how to test the Optional Parameters? 

Here is the answer


            MyClass myclass = new MyClass();

            myclass.MyMethod(1);

Note that we're intentionally left the parameters for b

Then the output will be


a is :1

b is :8
In MyMethod - With Parameters int a, int b

Lets dig more into this by adding more methods


        // Adding another overload method with double parameter

        public void MyMethod(double db)
        {
            Console.WriteLine("In MyMethod (One Double input)- With Parameters Double ab);
        }


Lets call Again the same method,

            myclass.MyMethod(1);

and the output will be (Same)

a is :1
b is :8
In MyMethod - With Parameters int a, int b

Because the CLR is looking for the exact match of the signature (here the input is of type int) so it hits the early method (with a two input as parameters)

  public void MyMethod(int a, int b)


Ok, then now, adding one more caller, 

            myclass.MyMethod(1.0);

Note that we're passing the exact signature type of Double,

Then the output will be

In MyMethod (One Double input)- With Parameter Double ab


So what's the catch, we can look that in the next part,


Meantime the full program for this module is



namespace OptionalParameters
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myclass = new MyClass();

            //myclass.MyMethod();

            /*             
              myclass.MyMethod();            
              myclass.MyMethod(1, 5);           
              myclass.MyMethod(1);          
              */
            myclass.MyMethod(1.0); 
            Console.ReadLine();
        }
    }
    class MyClass
    {
        public void MyMethod()
        {
            Console.WriteLine("In MyMethod - No Parameters");
        }
        public void MyMethod(int a = 10)
        {
            Console.WriteLine("In MyMethod - Single Parameters");
        }
        public void MyMethod(int a, int b = 8)
        {
            Console.WriteLine("a is :{0} ", a); Console.WriteLine("b is :{0} ", b);
            Console.WriteLine("In MyMethod - With Parameters int a, int b");
        }
        
        // Adding another overload method with double parameter 
        public void MyMethod(double db)
        {
            Console.WriteLine("In MyMethod (One Double input)- With Parameters int a, int b");
        }
    }

}







Comments

Popular posts from this blog

Using of global variables in C# - Drawbacks & Solutions

How using global variables can have implications on the design, maintainability, and test-ability of C# code: Harder to understand and reason about the code:       class Program     {         public static int globalCounter = 0;         static void Main()         {             globalCounter++;             Console.WriteLine(globalCounter);         }     }   In this example, the global variable globalCounter is accessible from anywhere in the program, including the Main method. It's not clear where the value of the globalCounter is updated, it could be updated in other methods or classes, making it harder to trace the flow of data and understand the source of bugs.   More prone to errors:       class Program     {         public static string globalString;         static void Main()         {             globalString = "Hello" ;             Method1();             Method2();         }         static void Method1()         {

Task Parallel Library (TPL) and Akka.NET Alternatives

Task Parallel Library (TPL) and Akka.NET are among the most commonly used libraries for parallel and concurrent programming in the .NET ecosystem. However, there are also several other options available, depending on your specific needs: Parallel Language Integrated Query (PLINQ) is a parallel programming feature of .NET that provides an easy and efficient way to perform operations on collections in parallel. LINQ (Language Integrated Query) is a powerful feature in .NET that allows developers to work with data in a more declarative and language-integrated manner. While LINQ queries are inherently sequential, PLINQ extends LINQ by providing parallel versions of the query operators, allowing some queries to execute faster by utilizing multiple processors or cores on a machine. PLINQ is great when you are working with large collections where operations might be CPU-intensive or I/O-bound and could potentially be sped up by parallel execution. Here is a simple example of a PLI

SOLID Principles with Real World examples in C#

  SOLID Principles with Real World examples in C#   SOLID principles are formed by using S Single Responsibility Principles (SRP) O Open Closed Principle (OCP) L Liskov’s Substitution Principle (LCP) I Interface Segregation Principle (ISP) D Dependency Inversion Principle (DIP)   S Single Responsibility Principles (SRP) There should never be more than one reason for a class to change, to be precise one class should have only one responsibility Single Responsibility Principles (SRP) Real world example, A perfect match for SRP is Microservices , a Microservice will not contain functionalities other than the one it is designated to do,  Example ·                   Order Processing Service, ·                   Shipment Management Service, ·                   User Authentication Service, ·                   Catalogue List Service       class OrderProcessor     {         public void Process(Order order)         {             // Check inven