Part 70 Making method parameters optional by using OptionalAttribute

۷۱.۱ K


۳

Tags c# using optionalattribute c# optionalattribute example Link for code samples used in the demo http://csharp-video-tutorials.blogspot.com/2013/05/making-method-parameters-optional-by.html Link for csharp, asp.net, ado.net, dotnet basics, mvc and sql server video tutorial playlists https://www.youtube.com/user/kudvenkat/playlists?view=1&sort=dd In this video, we will discuss making method parameters optional by using OptionalAttribute that is present in System.Runtime.InteropServices namespace This method allows us to add any number of integers. public static void AddNumbers(int firstNumber, int secondNumber, int[] restOfTheNumbers) { int result = firstNumber + secondNumber; foreach (int i in restOfTheNumbers) { result += i; } Console.WriteLine("Total = " + result.ToString()); } 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 an empty integer array as the argument for the 3rd parameter. AddNumbers(10, 20, new int[]{}); We can make the 3rd parameter optional by using OptionalAttribute that is present in System.Runtime.InteropServices namespace. Make sure you have "using" declaration for System.Runtime.InteropServices namespace. public static void AddNumbers(int firstNumber, int secondNumber, [Optional] int[] restOfTheNumbers) { int result = firstNumber + secondNumber; // loop thru restOfTheNumbers only if it is not null // otherwise you will get a null reference exception if (restOfTheNumbers != null) { foreach (int i in restOfTheNumbers) { result += i; } } Console.WriteLine("Total = " + result.ToString()); } So, if we want to add just 2 numbers, we can now use the function as shown below. AddNumbers(10, 20);

Published by: kudvenkat
Published at: ۶ years ago
Category: