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

Task Parallel Library (TPL) and Akka.NET: Differences

Task Parallel Library (TPL) and Akka.NET are both powerful tools in the .NET ecosystem for handling parallelism and concurrency, but they serve different purposes and use different models of computation. Here are some key differences:s 1.    Actor Model vs Task-Based Model: Akka.NET is built around the actor model, where actors are the fundamental units of computation and they communicate by exchanging messages. TPL, on the other hand, is task-based. It's designed to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. TPL uses tasks (which are independently executing work units) and provides various ways to control and coordinate them. 2.    Fault Tolerance: One of the key features of Akka.NET is its built-in fault tolerance. It has a "let-it-crash" philosophy, where the system is designed to self-heal from errors. If an actor fails, its parent actor can decide on the supervision strategy: either to resta

Extension Methods - Advanced

Here we will see how can we use the Extension Methods in advanced manner in other types Imagine you often need to retrieve items from a List based on a custom criterion that the built-in LINQ methods don't cover. Extension Methods for Lists: Filtering based on Custom Criteria And the output would be   Extending Enums: Displaying Descriptive Strings Output: Extending DateTime: Calculating Age     Output: The code samples can be found at https://github.com/oneananda/C_Sharp_Examples/tree/main/ExtensionMethods