Part 70 Making method parameters optional by using OptionalAttribute



3
88475

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 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?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: 11 years ago Category: آموزشی