Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Override with different parameters?

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?

like image 838
Qinusty Avatar asked Dec 18 '14 12:12

Qinusty


1 Answers

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
    }
}
like image 81
Yuval Itzchakov Avatar answered Oct 03 '22 21:10

Yuval Itzchakov