Part 68 Making method parameters optional using method overloading



4
90002

Tags c# params null c# optional parameter null c# optional parameter nullable c# parameter nullable c# parameter int null c# optional int parameters c# method overloading vs optional parameters Link for code samples used in the demo http://csharp-video-tutorials.blogspot.com/2013/05/part-68-making-method-parameters.html Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help. https://www.youtube.com/channel/UC7sEwIXM_YfAMyonQCrGfWA/?sub_confirmation=1 Link for csharp, asp.net, ado.net, dotnet basics, mvc and sql server video tutorial playlists https://www.youtube.com/user/kudvenkat/playlists?sort=dd&view=1 In this video, we will discuss making method parameters optional using method overloading This method allows us to add any number of integers. public static void AddNumbers(int firstNumber, int secondNumber, int[] restOfNumbers) { int result = firstNumber + secondNumber; if (restOfNumbers != null) { foreach(int i in restOfNumbers) { result += i; } } Console.WriteLine("Sum = " + result); } If we want to add 5 integers - 10, 20, 30, 40 and 50. We call the method as shown below. AddNumbers(10, 20, new int[]{30, 40, 50}); At the moment all the 3 parameters are mandatory. If I want to add just 2 numbers, then I can invoke the method as shown below. Notice that, I am passing null as the argument for the 3rd parameter. AddNumbers(10, 20, null); We can make the 3rd parameter optional by overloading AddNumbers() function as shown below. public static void AddNumbers(int firstNumber, int secondNumber) { AddNumbers(firstNumber, secondNumber, null); } Now, we have 2 overloaded versions of AddNumbers() function. If we want to add just 2 numbers, then I can use the overloaded version of AddNumbers() function, that takes 2 parameters as shown below. AddNumbers(10, 20); If I want to add 3 or more numbers, then I can use the overloaded version of AddNumbers() function, that takes 3 parameters as shown below. AddNumbers(10, 20, new int[] { 30, 40 });

Published by: kudvenkat Published at: 10 years ago Category: آموزشی