C# Override with different parameters?
34,492
Solution 1
When overriding a virtual
method, you must keep the original "contract" of the method, which in your case is a string a
variable.
In order to do what you want, you can create a virtual overload which takes two strings:
public class A
{
public virtual void DoSomething(string a)
{
// perform something
}
public virtual void DoSomething(string a, string b)
{
// perform something
}
}
public class B : A
{
public override void DoSomething(string a, string b)
{
// perform something slightly different using both strings
}
}
If what you want is to accept N strings in your method, you can use the params
keyword:
public class A
{
public virtual void DoSomething(params string[] allStrings)
{
// Do something with the first string in the array
// perform something
}
}
Solution 2
Slight necro, but when you overload you can call the original method from the new one.
so
public class B : A {
public virtual void DoSomething (string a, string b) {
base.DoSomething(_a);
//Do B things here
}
}
This allows you to modify the method instead of completely redoing it :)
Author by
Qinusty
Updated on March 28, 2020Comments
-
Qinusty over 4 years
Here is an example of what I am looking to do.
public class A { public virtual void DoSomething(string a) { // perform something } } public class B : A { public Override void DoSomething(string a, string b) { // perform something slightly different using both strings } }
So I want to override DoSomething from class A and allow it to pass a second parameter. Is this possible?
-
Qinusty over 9 yearsIs there any way of doing this? I am creating a 2 types of linked lists and would like the second to have a priority parameter when adding to the list.
-
msporek over 9 yearsYou should just define the new method in the second class (I mean in class B). This new method will have two parameters, and then this new method can call the original method, this way: base.DoSometing("..."); Methods in your derived classes can call methods from your base classes with base.<MethodName>. This way you can reuse the existing code to some extent.