Lets See How We Can Do This. I Have Create A Simple Console Application. In That Create A Static Method Called "SayHello" Which Takes Two String Parameters As "First Name" And "Last Name".
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Optional_Parameter { class Program { static void Main(string[] args) { SayHello("Nifal", "Nizar"); Console.ReadLine(); } static void SayHello(string firstName, string lastName) { Console.WriteLine("Hello {0} {1}", firstName, lastName); } } } |
If You Run This You Will Get The Output In The Console As Below.
Hello Nifal Nizar
Lets Make The "Last Name" Parameter Optional. Simply In The Method Give A Default Value To The "Last Name" Parameter. In My Case I'm Giving Empty String To It. Lets See The Code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Optional_Parameter { class Program { static void Main(string[] args) { SayHello("Nifal"); Console.ReadLine(); } static void SayHello(string firstName, string lastName = "") { Console.WriteLine("Hello {0} {1}", firstName, lastName); } } } |
Now Run And See The Output.
Hello Nifal
Same Like This You Can Make More Optional Parameters. Hope You Got The Knowledge Of Optional Parameter.
No comments:
Post a Comment