locked
How can i give an optional parameter to an abstract procedure ? RRS feed

  • Question

  • User1253338400 posted

    Hi I have the following:

    a definition as follows:

    public abstract class MyBase
    {
         public abstract void MyFunction1(Param1 parameter, DataRow Row, long lineNo)

         etc etc
    }

    in an abstract class.


    I call this as follows

    MyFunction1(param, row, LineNo)

    How can i give this an optional parameter.


    Also , there are many other classes that inherit from the base class above (MyBase) and make use of the MyFunction1 call, so does that mean I have to give all those methods optional parameters as well ?


    Thanks

    Tuesday, July 23, 2019 5:45 AM

Answers

  • User-821857111 posted

    You can't specify an optional parameter in an abstract method. What you can do is to provide an overload that takes the "optional" parameter:

     public abstract void MyFunction1(Param1 parameter, DataRow Row, long lineNo, string optional){}

    Inherited classes will have to provide implementations for both methods, of course.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 23, 2019 7:04 AM

All replies

  • User-821857111 posted

    You can't specify an optional parameter in an abstract method. What you can do is to provide an overload that takes the "optional" parameter:

     public abstract void MyFunction1(Param1 parameter, DataRow Row, long lineNo, string optional){}

    Inherited classes will have to provide implementations for both methods, of course.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 23, 2019 7:04 AM
  • User753101303 posted

    Hi,

    You can use int lineNo=0 as usual: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments#optional-arguments

    You'll have to keep using the same signature declaration but your abstract method can use non optional parameters while the concrete version uses optional parameters (which means they get a default value if don't pass explicitely a value) ie you can do:

       abstract class DemoBase
       {
          public abstract void Test(int i); // non optional
       }
       class Demo : DemoBase
       {
          public override void Test(int i=10) // 10 if no value passed explicitely
          {
            Console.WriteLine(i);
          }
       }
    
    and use later just MyDemo.Test(); or MyDemo.Test(5);

    Tuesday, July 23, 2019 7:41 AM