I have an abstract class which has a method with params parameter as below. I want to override and hide this method with a method which takes certain number of parameters instead of params in inheriting class.
public abstract class BaseClass{
public List<int> list = new List<int>();
public void Add(params int[] numbers){
list.AddRange(numbers);
}
}
public class ChildClass : BaseClass{
public override void Add(int a, int b, int c){
base.Add(a, b, c);
}
}
This works but Add function of base class is still visible to outside and Add function in the child class doesn't seem to override it. Is there a way?
I want to override and hide this method with a method which takes certain number of parameters instead of params in inheriting class.
You can't. That would break inheritance. Consider the following code:
BaseClass bc = new ChildClass();
bc.Add(0, 1);
That has to compile - so what would you expect it to do? If you're expecting the method with 3 parameters to replace the original, then presumably you don't want that to compile - but the compile-time type of bc
is just BaseClass
, not ChildClass
.
You can overload BaseClass.Add
(you don't need new
because it's not got the same signature as the base class method), but you can't replace it with a more restrictive form.
See more on this question at Stackoverflow