Qinusty
Qinusty

Reputation: 339

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?

Upvotes: 14

Views: 51648

Answers (6)

Rafael Ribeiro
Rafael Ribeiro

Reputation: 11

public class BaseClass
{
    //the '= null' makes it that the subsequent classes doesn't necessarily need to pass parameters
    public virtual void InitializeOrWhatever(object[] parameters = null)
    {
    }

    //this method allows that others can check their parameters to se if it's the right type
    public static bool VerifyParameter<T>(object obj, out T cast)
    {
        cast = (T)obj;
            if (cast != null)
                return true;
            else
            {
                ParametersError(typeof(T));
                return false;
            }
        }

    //this method prints out a massage if the type doesn't match. Also can be changed from outside classes
    public static void ParametersError(Type t, string addition = "")
            => print($"Parameters sent on {t} initialization are not correct!\n{addition}")
}

public class DerivedClass : BaseClass
{
    float Number;
    bool Used;

    public override void InitializeOrWhatever(object[] parameters = null)
    {
        //executes the base method. Important if the parent class must execute something first
        base.Initialize(controller, parameters);

        //custom message sent from derived class
        if (parameters == null)
        {
            ParametersError(this.GetType(), "No parameters sent!");
            return;
        }

        if (VerifyParameter(parameters[0], out float number))
            Number = number;

        if (VerifyParameter(parameters[1], out bool used))
            Used = used;
    }
}

Upvotes: 1

Mechandrius
Mechandrius

Reputation: 357

There is a way. It requires some code though. You create a master class fex. 'MachineParams'. Then create subclasses like 'MachineParamsGeneral', 'MachineParamsDetail'.

Your function can now be like:

public override void Setup(MachineParams p)
{
// since you know what subclass this is inside, you can simple cast
MachineParamsGeneral g = (MachineParamsGeneral)p;
float paramExample = p.paramExample;
}

You need to consider if this solution is "handy" enough for your scale.

A second solution:

public override void Setup(params object[] p ..)
{
// you need to know the arrangement of values inside the object array
float x = (float)p[0]; // not strictly speaking type-safe
}

Upvotes: 1

Rarceth
Rarceth

Reputation: 41

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 :)

Upvotes: 4

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149518

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
    }
}

Upvotes: 18

nka
nka

Reputation: 41

No, this would be overloading. Since the logic would be 'slightly different' it sounds like you would need two different methods anyway? You could put your similar logic in a 3rd method and call that from both DoSomething(string A) and DoSomething(string A, string B)

Upvotes: 0

msporek
msporek

Reputation: 1197

No, this won't work. When overriding the methods needs to have the same prototype.

Upvotes: 0

Related Questions