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. can i use optional parameters

can i use optional parameters

Scheduled Pinned Locked Moved C#
csharpquestion
8 Posts 6 Posters 0 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.
  • S Offline
    S Offline
    Sonia Gupta
    wrote on last edited by
    #1

    Optional parameters does not exist in C# ?

    Sonia Gupta Soniagupta1@yahoo.co.in Yahoo messengerId-soniagupta1 Love is Friendship and Friendship is Love....

    H D P 3 Replies Last reply
    0
    • S Sonia Gupta

      Optional parameters does not exist in C# ?

      Sonia Gupta Soniagupta1@yahoo.co.in Yahoo messengerId-soniagupta1 Love is Friendship and Friendship is Love....

      H Offline
      H Offline
      Hessam Jalali
      wrote on last edited by
      #2

      Here is from MSDN

      Some languages (such as the Managed Extensions for C++ and Microsoft Visual Basic 2005) support the assignment of default values to arguments. For example, the following is a legitimate Visual Basic 2005 declaration that has default values for two of the arguments.

      Visual Basic Copy Code Public Sub MyMethod (a as Integer, _ Optional b as Double = 1.2, _ Optional c as Integer = 1)

      You can use a parameter attribute to assign a default parameter value.

      In Visual Basic and C++, optional parameters can be omitted when the method is called. In C# values must be specified for optional arguments.

      For example, all the following Visual Basic and C++ examples are valid calls for MyMethod.

      Visual Basic Copy Code
      MyMethod(10, 55.3, 12) MyMethod(10, 1.3) ' c == 1 MyMethod(11) ' b == 1.2, c == 1

      C++ Copy Code
      MyMethod(10, 55.3, 12); MyMethod(10, 1.3); // c == 1 MyMethod(11); // b == 1.2, c == 1

      To retrieve the default value of an argument using reflection, get a ParameterInfo object for the parameter, and then retrieve the default value using the ParameterInfo.DefaultValue property. If there is no default value, the property returns Value.DBNull.

      The following example displays the default values for MyMethod to the console.

      Visual Basic Copy Code

      Dim m As MethodInfo = t.GetMethod("MyMethod") Dim ps As ParameterInfo() = m.GetParameters() Dim i As Integer For i = 0 To ps.Length - 1 Console.WriteLine("Default Value == {0}", ps(i).DefaultValue) Next i

      C# Copy Code

      MethodInfo m = t.GetMethod("MyMethod"); ParameterInfo[] ps = m.GetParameters(); for (int i = 0; i < ps.Length; i++) { Console.WriteLine("Default Value == {0}", ps[i].DefaultValue); }

      C++ Copy Code

      MethodInfo m = t->GetMethod("MyMethod"); ParameterInfo[] ps = m->GetParameters(); for (int i = 0; i < ps.Length; i++) { Console::WriteLine(S"Default Value == {0}", ps[i]->DefaultValue); }

      To invoke methods that have arguments with default values, use Type.Missing as a parameter value to the InvokeMember method. This enables the late-binding service to use the default value for the indicated parameter value. If Type.Missing is passed for a parameter that has no default value, an ArgumentException is thrown. It is important to note that not all compilers' binding mechanisms might respect these rules for Type.Missing

      T 1 Reply Last reply
      0
      • H Hessam Jalali

        Here is from MSDN

        Some languages (such as the Managed Extensions for C++ and Microsoft Visual Basic 2005) support the assignment of default values to arguments. For example, the following is a legitimate Visual Basic 2005 declaration that has default values for two of the arguments.

        Visual Basic Copy Code Public Sub MyMethod (a as Integer, _ Optional b as Double = 1.2, _ Optional c as Integer = 1)

        You can use a parameter attribute to assign a default parameter value.

        In Visual Basic and C++, optional parameters can be omitted when the method is called. In C# values must be specified for optional arguments.

        For example, all the following Visual Basic and C++ examples are valid calls for MyMethod.

        Visual Basic Copy Code
        MyMethod(10, 55.3, 12) MyMethod(10, 1.3) ' c == 1 MyMethod(11) ' b == 1.2, c == 1

        C++ Copy Code
        MyMethod(10, 55.3, 12); MyMethod(10, 1.3); // c == 1 MyMethod(11); // b == 1.2, c == 1

        To retrieve the default value of an argument using reflection, get a ParameterInfo object for the parameter, and then retrieve the default value using the ParameterInfo.DefaultValue property. If there is no default value, the property returns Value.DBNull.

        The following example displays the default values for MyMethod to the console.

        Visual Basic Copy Code

        Dim m As MethodInfo = t.GetMethod("MyMethod") Dim ps As ParameterInfo() = m.GetParameters() Dim i As Integer For i = 0 To ps.Length - 1 Console.WriteLine("Default Value == {0}", ps(i).DefaultValue) Next i

        C# Copy Code

        MethodInfo m = t.GetMethod("MyMethod"); ParameterInfo[] ps = m.GetParameters(); for (int i = 0; i < ps.Length; i++) { Console.WriteLine("Default Value == {0}", ps[i].DefaultValue); }

        C++ Copy Code

        MethodInfo m = t->GetMethod("MyMethod"); ParameterInfo[] ps = m->GetParameters(); for (int i = 0; i < ps.Length; i++) { Console::WriteLine(S"Default Value == {0}", ps[i]->DefaultValue); }

        To invoke methods that have arguments with default values, use Type.Missing as a parameter value to the InvokeMember method. This enables the late-binding service to use the default value for the indicated parameter value. If Type.Missing is passed for a parameter that has no default value, an ArgumentException is thrown. It is important to note that not all compilers' binding mechanisms might respect these rules for Type.Missing

        T Offline
        T Offline
        Tormod Fjeldskaar
        wrote on last edited by
        #3

        One way to solve it is to use polymorphism method overloading:

        private void MyMethod(int x, int y, int z)
        {...}

        private void MyMethod(int x, int y)
        {
        MyMethod(x, y, 10); //gives z default value 10
        }

        private void MyMethod(int x)
        {
        MyMethod(x, 5); //gives y default value 5
        }

        -- modified at 2:56 Tuesday 7th August, 2007

        S 1 Reply Last reply
        0
        • T Tormod Fjeldskaar

          One way to solve it is to use polymorphism method overloading:

          private void MyMethod(int x, int y, int z)
          {...}

          private void MyMethod(int x, int y)
          {
          MyMethod(x, y, 10); //gives z default value 10
          }

          private void MyMethod(int x)
          {
          MyMethod(x, 5); //gives y default value 5
          }

          -- modified at 2:56 Tuesday 7th August, 2007

          S Offline
          S Offline
          Sonia Gupta
          wrote on last edited by
          #4

          i think we r astraying from the right topic.don;t u thnk it is function overloading.

          Sonia Gupta Soniagupta1@yahoo.co.in Yahoo messengerId-soniagupta1 Love is Friendship and Friendship is Love....

          C 1 Reply Last reply
          0
          • S Sonia Gupta

            i think we r astraying from the right topic.don;t u thnk it is function overloading.

            Sonia Gupta Soniagupta1@yahoo.co.in Yahoo messengerId-soniagupta1 Love is Friendship and Friendship is Love....

            C Offline
            C Offline
            Christian Graus
            wrote on last edited by
            #5

            No, this is the only way to simulate optional parameters in C#

            Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

            S 1 Reply Last reply
            0
            • C Christian Graus

              No, this is the only way to simulate optional parameters in C#

              Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

              S Offline
              S Offline
              Sonia Gupta
              wrote on last edited by
              #6

              ok

              Sonia Gupta Soniagupta1@yahoo.co.in Yahoo messengerId-soniagupta1 Love is Friendship and Friendship is Love....

              1 Reply Last reply
              0
              • S Sonia Gupta

                Optional parameters does not exist in C# ?

                Sonia Gupta Soniagupta1@yahoo.co.in Yahoo messengerId-soniagupta1 Love is Friendship and Friendship is Love....

                D Offline
                D Offline
                Diana Fernandez
                wrote on last edited by
                #7

                See the code snippet copied from MSDN. Hope this helps... using System; public class MyClass { public static void UseParams(params int[] list) { for (int i = 0 ; i < list.Length; i++) { Console.WriteLine(list[i]); } Console.WriteLine(); } public static void UseParams2(params object[] list) { for (int i = 0 ; i < list.Length; i++) { Console.WriteLine(list[i]); } Console.WriteLine(); } static void Main() { UseParams(1, 2, 3); UseParams2(1, 'a', "test"); // An array of objects can also be passed, as long as // the array type matches the method being called. int[] myarray = new int[3] {10,11,12}; UseParams(myarray); } }

                1 Reply Last reply
                0
                • S Sonia Gupta

                  Optional parameters does not exist in C# ?

                  Sonia Gupta Soniagupta1@yahoo.co.in Yahoo messengerId-soniagupta1 Love is Friendship and Friendship is Love....

                  P Offline
                  P Offline
                  Pete OHanlon
                  wrote on last edited by
                  #8

                  One way to do this, is to use the params keyword. The only problem is that you have no control over what the developer puts in, but this is how things like string.Format work. Example:

                  public void DoSomething(params string[] items)
                  {
                    if (items != null && items.Length > 0)
                    {
                      foreach (string item in item)
                      {
                        // Do something.
                      }
                    }
                  }
                  

                  Deja View - the feeling that you've seen this post before.

                  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