Share via


How can i give an optional parameter to an abstract procedure ?

Question

Tuesday, July 23, 2019 5:45 AM

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

All replies (2)

Tuesday, July 23, 2019 7:04 AM âś…Answered

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.


Tuesday, July 23, 2019 7:41 AM

Hi,

You can use int lineNo=0 as usual: /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);