In this case, we will have to be creative. Simply ignoring the arguments extrapolates the design of the C language#.
First, the method, to be overwritten, needs to be virtual
:
public virtual int AnyMethod()
{
throw new NotImplementedException ( "This method is not implemented" );
}
Second, it is possible to make an implementation that receives N arguments of a certain type. Or, still, of object
, but that if you like to live with emotion:
public virtual int AnyMethod(params int[] numeros)
{
throw new NotImplementedException ( "This method is not implemented" );
}
Third, you can rather go on deriving polymorphisms with different arguments in the derived class. Something like this:
public class B: A
{
public override int AnyMethod(params int[] lista)
{
return lista.Sum(x => x);
}
public int AnyMethod(int a, int b)
{
return AnyMethod(new int[] {a, b});
}
}
Then we can have a specific method with 2 arguments and another with N.
public class Program
{
public static void Main()
{
Console.WriteLine(new B().AnyMethod(1, 2));
Console.WriteLine(new B().AnyMethod(1, 2, 3));
}
}
I made you a Fiddle.
At the request of the questioner, I will also explain one more option, which is the reintroduction of methods, made by the word modifier new
in the method.
new
would be the equivalent of reintroduce
of Delphi, where we explicitly override a base class method in the derived class. The difference to override
is that the base class method is can be called using base.AnyMethod
, while using new
the base class method is totally ignored.
In the scope of the example, if there was a method public int AnyMethod(int a, int b)
in the base class, it would be something like:
public new int AnyMethod(int a, int b)
{
return a + b;
}
This type of operator, as well as the addition of more polymorphisms in derived classes, can be prevented by using the modifier sealed
in the class declaration.
I upgraded Fiddle by now placing a polymorphism for three operators.
In this case, B inherits A?
– Leonel Sanches da Silva
Yes, I just modified it
– Matheus Saraiva