Part 67 Optional parameters in c#



4
108926

Tags how to pass optional parameter in c# method c# method parameter default value c# parameter array c# method params keyword c# optionalattribute example c# optionalattribute default value c# default method parameters How are parameters passed in C# Link for code samples used in the demo http://csharp-video-tutorials.blogspot.com/2013/05/part-67-optional-parameters-in-c.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 the different ways that are available to make method parameters optional. This is a very common intervew question. There are 4 ways that can be used to make method parameters optional. 1. Use parameter arrays 2. Method overloading 3. Specify parameter defaults 4. Use OptionalAttribute that is present in System.Runtime.InteropServices namespace Using parameter arrays, to make method parameters optional: AddNumbers function, allows the user to add 2 or more numbers. firstNumber and secondNumber parameters are mandatory, where as restOfTheNumbers parameter is optional. public static void AddNumbers(int firstNumber, int secondNumber, params object[] restOfTheNumbers) { int result = firstNumber + secondNumber; foreach (int i in restOfTheNumbers) { result += i; } Console.WriteLine("Total = " + result.ToString()); } Please note that, a parameter array must be the last parameter in a formal parameter list. The following function will not compile. public static void AddNumbers(int firstNumber, params object[] restOfTheNumbers, int secondNumber) { // Function implementation } If the user wants to add just 2 numbers, then he would invoke the method as shown below. AddNumbers(10, 20); On the other hand, if the user wants to add 5 numbers, then he would invoke the method as shown below. AddNumbers(10, 20, 30, 40, 50); or AddNumbers(10, 20, new object[] { 30, 40, 50 }); In our next video, we will discuss method overloading, specifying parameter defaults & using OptionalAttribute.

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