Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Default or optional Parameters in C#

Default or optional Parameters in C#

Scheduled Pinned Locked Moved C#
csharpc++help
29 Posts 21 Posters 10 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • I indian143

    Hi, We have default parameters in C++ like at the time of function definition we can give some default value to a parameter. Is there anyhting similar in C#. Because when I gave like in the below line it was giving me error in the C#, can I use this thing in the C#

    public static void sample(int i=100, string s=string.Empty, bool b=true)
    {
    ///Something
    }

    Thanks & Regards, Md. Abdul Aleem NIIT technologies

    D Offline
    D Offline
    deepakshukla79
    wrote on last edited by
    #9

    You can use optional parameter . you can this by this way class Program { static void Main(string[] args) { Console.WriteLine(Sum(1, 2, 3).ToString()); Console.WriteLine(Sum( 2, 3).ToString()); Console.ReadLine(); } static int Sum(params int[] li) { int sum=0; for ( int i = 0 ; i < li.Length ; i++ ) { sum+=li[i]; } return sum; } }

    H 1 Reply Last reply
    0
    • D deepakshukla79

      You can use optional parameter . you can this by this way class Program { static void Main(string[] args) { Console.WriteLine(Sum(1, 2, 3).ToString()); Console.WriteLine(Sum( 2, 3).ToString()); Console.ReadLine(); } static int Sum(params int[] li) { int sum=0; for ( int i = 0 ; i < li.Length ; i++ ) { sum+=li[i]; } return sum; } }

      H Offline
      H Offline
      Hiren solanki
      wrote on last edited by
      #10

      You've provided a way which can be only applicable to Integer, Try to expand it for all type of object passed in method. Like instead of receiving data only in a array of int[], Receive it in object[]. and further check of every item in array whether it's bool,string,object of custom class,float,decimal. That would be quite cumbersome, optional parameter is the good way , I guess.

      Regards, Hiren.

      My Recent Article: - Way to know which control have raised PostBack
      My Recent Tip/Trick: - Remove HTML Tag, get plain Text

      1 Reply Last reply
      0
      • R Roger Wright

        You can accomplish a similar effect by defining several versions of the same function, each with a different signature:

        public static void sample(int i, string a)
        {
        bool b= true;
        //more stuff
        }

        public static void sample(int i, bool b)
        {
        string s = string.Empty;
        //more stuff
        }

        public static void sample(string a, bool b)
        {
        int i = 100;
        //more stuff
        }

        etc... If I remember my reading correctly, at run time the calling statement will be matched to the version with matching parameters, and the function will fill in the missing values with the predefined defaults. Of course, I may be a complete idiot - I'm fairly new to C#. But it's what I would try if I really needed to do this. :)

        Will Rogers never met me.

        G Offline
        G Offline
        Gary Wheeler
        wrote on last edited by
        #11

        I usually implement that pattern as follows in C# 3.5:

        public static void sample(int i, string a)
        {
        _sample(i,false,true,a);
        }
        public static void sample(int i, bool b)
        _sample(i,false,b,string.Empty);
        }
        public static void sample(string a, bool b)
        {
        _sample(100,false,b,a);
        }
        private static void _sample(int i,bool a,bool b,string a_string)
        {
        // implement 'sample' operation
        }

        Software Zen: delete this;

        E 1 Reply Last reply
        0
        • I indian143

          Hi, We have default parameters in C++ like at the time of function definition we can give some default value to a parameter. Is there anyhting similar in C#. Because when I gave like in the below line it was giving me error in the C#, can I use this thing in the C#

          public static void sample(int i=100, string s=string.Empty, bool b=true)
          {
          ///Something
          }

          Thanks & Regards, Md. Abdul Aleem NIIT technologies

          S Offline
          S Offline
          Spectre_001
          wrote on last edited by
          #12

          Not exactly elegant but...

          public static void sample(int i, string s, bool b)
          {
          if (i == default(int)) { i = 100; }
          if (s == default(string)) { s = string.Empty; }
          if (b == default(bool)) { b = true; }

          // The rest of your method...
          

          }

          Works in .NET Framework 3.5.

          Kevin Rucker, Application Programmer QSS Group, Inc. United States Coast Guard OSC Kevin.D.Rucker@uscg.mil "Programming is an art form that fights back." -- Chad Hower

          D P S 3 Replies Last reply
          0
          • A Abhinav S

            You need to use .Net 4.0.

            The funniest thing about this particular signature is that by the time you realise it doesn't say anything it's too late to stop reading it. My latest tip/trick Visit the Hindi forum here.

            P Offline
            P Offline
            PIEBALDconsult
            wrote on last edited by
            #13

            C# 4 !

            F 1 Reply Last reply
            0
            • I indian143

              Hi, We have default parameters in C++ like at the time of function definition we can give some default value to a parameter. Is there anyhting similar in C#. Because when I gave like in the below line it was giving me error in the C#, can I use this thing in the C#

              public static void sample(int i=100, string s=string.Empty, bool b=true)
              {
              ///Something
              }

              Thanks & Regards, Md. Abdul Aleem NIIT technologies

              H Offline
              H Offline
              Hari Om Prakash Sharma
              wrote on last edited by
              #14

              visual studio 2010

              First and the Foremost: FIGHT TO WIN

              1 Reply Last reply
              0
              • I indian143

                Hi, We have default parameters in C++ like at the time of function definition we can give some default value to a parameter. Is there anyhting similar in C#. Because when I gave like in the below line it was giving me error in the C#, can I use this thing in the C#

                public static void sample(int i=100, string s=string.Empty, bool b=true)
                {
                ///Something
                }

                Thanks & Regards, Md. Abdul Aleem NIIT technologies

                H Offline
                H Offline
                hground
                wrote on last edited by
                #15

                VB .NET has had optional parameters for some time :) Looks like it took C# a while to catch up :) (Yeah - I know! I shouldn't throw rocks at hornet's nests, but sometimes you just can't resist!)

                1 Reply Last reply
                0
                • I indian143

                  Hi, We have default parameters in C++ like at the time of function definition we can give some default value to a parameter. Is there anyhting similar in C#. Because when I gave like in the below line it was giving me error in the C#, can I use this thing in the C#

                  public static void sample(int i=100, string s=string.Empty, bool b=true)
                  {
                  ///Something
                  }

                  Thanks & Regards, Md. Abdul Aleem NIIT technologies

                  J Offline
                  J Offline
                  jlafay
                  wrote on last edited by
                  #16

                  That's possible in C# 4, and the same syntax applies. -jeff

                  1 Reply Last reply
                  0
                  • I indian143

                    Hi, We have default parameters in C++ like at the time of function definition we can give some default value to a parameter. Is there anyhting similar in C#. Because when I gave like in the below line it was giving me error in the C#, can I use this thing in the C#

                    public static void sample(int i=100, string s=string.Empty, bool b=true)
                    {
                    ///Something
                    }

                    Thanks & Regards, Md. Abdul Aleem NIIT technologies

                    G Offline
                    G Offline
                    grgran
                    wrote on last edited by
                    #17

                    As already pointed out, optional, default and named parameters are available in .NET 4.0 Interestingly, if you do use them the code analysis tool slaps your hand about it, requesting that you create overloads with the defaults set in method. G

                    P 1 Reply Last reply
                    0
                    • I indian143

                      Hi, We have default parameters in C++ like at the time of function definition we can give some default value to a parameter. Is there anyhting similar in C#. Because when I gave like in the below line it was giving me error in the C#, can I use this thing in the C#

                      public static void sample(int i=100, string s=string.Empty, bool b=true)
                      {
                      ///Something
                      }

                      Thanks & Regards, Md. Abdul Aleem NIIT technologies

                      P Offline
                      P Offline
                      Paladin2000
                      wrote on last edited by
                      #18

                      No, you can't set default values. But you can use an overload to accomplish something similar.

                      public static void sample(int i, string s, bool b)
                      {
                      ///Something
                      }

                      public static void sample()
                      {
                      sample(100, string.Empty, true);
                      }

                      public static void sample(int i)
                      {
                      sample(i, string.Empty, true);
                      }

                      ///Etc...

                      1 Reply Last reply
                      0
                      • S Spectre_001

                        Not exactly elegant but...

                        public static void sample(int i, string s, bool b)
                        {
                        if (i == default(int)) { i = 100; }
                        if (s == default(string)) { s = string.Empty; }
                        if (b == default(bool)) { b = true; }

                        // The rest of your method...
                        

                        }

                        Works in .NET Framework 3.5.

                        Kevin Rucker, Application Programmer QSS Group, Inc. United States Coast Guard OSC Kevin.D.Rucker@uscg.mil "Programming is an art form that fights back." -- Chad Hower

                        D Offline
                        D Offline
                        djdanlib 0
                        wrote on last edited by
                        #19

                        Wait, how does that even work? I've never even heard of something like that. I am intrigued. Is this what you're doing? http://msdn.microsoft.com/en-us/library/xwth0h0d%28v=VS.80%29.aspx[^]

                        S 1 Reply Last reply
                        0
                        • D djdanlib 0

                          Wait, how does that even work? I've never even heard of something like that. I am intrigued. Is this what you're doing? http://msdn.microsoft.com/en-us/library/xwth0h0d%28v=VS.80%29.aspx[^]

                          S Offline
                          S Offline
                          Spectre_001
                          wrote on last edited by
                          #20

                          Yes, it just returns the framework's default value for the type specified.

                          Kevin Rucker, Application Programmer QSS Group, Inc. United States Coast Guard OSC Kevin.D.Rucker@uscg.mil "Programming is an art form that fights back." -- Chad Hower

                          1 Reply Last reply
                          0
                          • P PIEBALDconsult

                            C# 4 !

                            F Offline
                            F Offline
                            Fabio Franco
                            wrote on last edited by
                            #21

                            LOL, please say it again, just one more time :laugh:

                            P 1 Reply Last reply
                            0
                            • G grgran

                              As already pointed out, optional, default and named parameters are available in .NET 4.0 Interestingly, if you do use them the code analysis tool slaps your hand about it, requesting that you create overloads with the defaults set in method. G

                              P Offline
                              P Offline
                              PIEBALDconsult
                              wrote on last edited by
                              #22

                              grgran wrote:

                              .NET 4.0

                              C# 4 dagnabit!!!

                              1 Reply Last reply
                              0
                              • F Fabio Franco

                                LOL, please say it again, just one more time :laugh:

                                P Offline
                                P Offline
                                PIEBALDconsult
                                wrote on last edited by
                                #23

                                Done, but I've now run out of attributes -- how do you do blinking?

                                1 Reply Last reply
                                0
                                • S Spectre_001

                                  Not exactly elegant but...

                                  public static void sample(int i, string s, bool b)
                                  {
                                  if (i == default(int)) { i = 100; }
                                  if (s == default(string)) { s = string.Empty; }
                                  if (b == default(bool)) { b = true; }

                                  // The rest of your method...
                                  

                                  }

                                  Works in .NET Framework 3.5.

                                  Kevin Rucker, Application Programmer QSS Group, Inc. United States Coast Guard OSC Kevin.D.Rucker@uscg.mil "Programming is an art form that fights back." -- Chad Hower

                                  P Offline
                                  P Offline
                                  PIEBALDconsult
                                  wrote on last edited by
                                  #24

                                  So, then, how would I specify 0, null, and false (?) when I want to?

                                  S 1 Reply Last reply
                                  0
                                  • S Spectre_001

                                    Not exactly elegant but...

                                    public static void sample(int i, string s, bool b)
                                    {
                                    if (i == default(int)) { i = 100; }
                                    if (s == default(string)) { s = string.Empty; }
                                    if (b == default(bool)) { b = true; }

                                    // The rest of your method...
                                    

                                    }

                                    Works in .NET Framework 3.5.

                                    Kevin Rucker, Application Programmer QSS Group, Inc. United States Coast Guard OSC Kevin.D.Rucker@uscg.mil "Programming is an art form that fights back." -- Chad Hower

                                    S Offline
                                    S Offline
                                    StephenPhillips
                                    wrote on last edited by
                                    #25

                                    Hmm, surely that misses the advantage of giving optional parameters, i.e. you can call the function without specifying all the input - using this form means you still need to give three values, or it doesn't match the function. Also, in this example, it's impossible to supply 'false' for the third value; false is the default value for a bool, so it would always become true.

                                    S 1 Reply Last reply
                                    0
                                    • I indian143

                                      Hi, We have default parameters in C++ like at the time of function definition we can give some default value to a parameter. Is there anyhting similar in C#. Because when I gave like in the below line it was giving me error in the C#, can I use this thing in the C#

                                      public static void sample(int i=100, string s=string.Empty, bool b=true)
                                      {
                                      ///Something
                                      }

                                      Thanks & Regards, Md. Abdul Aleem NIIT technologies

                                      J Offline
                                      J Offline
                                      Jeff Connelly
                                      wrote on last edited by
                                      #26

                                      Yes, the C# lost that feature from "primitive" C++. You get it back with interest in C# 4.0 - not only can you provide default parameter values, you can also name your parameters and provide them in any order you want. For example, in C++ you had to order your function parameters correctly, so that the ones with default values came at the end. void foo(int i = 1, int j = 0, int k) This didn't work, because what does the call foo(1, 2) mean? In C# 4.0, you can do that. foo(k: 0, j: 1) So add "named" parameters (arguments) to the feature, which was not available in C++.

                                      1 Reply Last reply
                                      0
                                      • S StephenPhillips

                                        Hmm, surely that misses the advantage of giving optional parameters, i.e. you can call the function without specifying all the input - using this form means you still need to give three values, or it doesn't match the function. Also, in this example, it's impossible to supply 'false' for the third value; false is the default value for a bool, so it would always become true.

                                        S Offline
                                        S Offline
                                        Spectre_001
                                        wrote on last edited by
                                        #27

                                        You're absolutely correct, the only way to truly emulate optional parameters like in VB would be to use overloads of the method like this:

                                        public static void sample(int i, string s, bool b)
                                        {
                                        // Do work here
                                        }

                                        public static void sample(int i)
                                        {
                                        sample(i, string.Empty, true);
                                        }

                                        public static void sample(int i, string s)
                                        {
                                        sample(i, s, true);
                                        }

                                        public static void sample(int i, bool b)
                                        {
                                        sample(i, string.Empty, b);
                                        }

                                        public static void sample(string s)
                                        {
                                        sample(100, s, true);
                                        }

                                        public static void sample(string s, bool b)
                                        {
                                        sample(100, s, b);
                                        }

                                        public static void sample (bool b)
                                        {
                                        sample(100, string.Empty, b);
                                        }

                                        public static void sample()
                                        {
                                        sample(100, string.Empty, true);
                                        }

                                        Which swiftly becomes unweildy once you get past three parameters.

                                        Kevin Rucker, Application Programmer QSS Group, Inc. United States Coast Guard OSC Kevin.D.Rucker@uscg.mil "Programming is an art form that fights back." -- Chad Hower

                                        1 Reply Last reply
                                        0
                                        • P PIEBALDconsult

                                          So, then, how would I specify 0, null, and false (?) when I want to?

                                          S Offline
                                          S Offline
                                          Spectre_001
                                          wrote on last edited by
                                          #28

                                          See the answer I posted to StephenPhillips.

                                          Kevin Rucker, Application Programmer QSS Group, Inc. United States Coast Guard OSC Kevin.D.Rucker@uscg.mil "Programming is an art form that fights back." -- Chad Hower

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups