Search code examples
c#functionvirtual-functionsout-parameters

How to override a virtual method that has an out parameter?


I have this virtual method in my base class:

public virtual bool AgregarEtapa(DateTime pFechaIngreso, EtapaEnvio.Etapas pEtapa, OficinaPostal pUbicacion, string pNombreRecibio, out string pMensajeError) 
{
    string mensajeError = "";
    bool sePuedeAgregar = false;

    // more code

    pMensajeError = mensajeError;
    return sePuedeAgregar;
}

and a method that overrides it in a child class, like this:

public override bool AgregarEtapa(DateTime pFechaIngreso, EtapaEnvio.Etapas pEtapa, OficinaPostal pUbicacion, string pNombreRecibio, out string pMensajeError)
{
    bool seHace = true;
    bool exito = false;

    // more code here

    if (seHace) 
    { 
        base.AgregarEtapa(pFechaIngreso, pEtapa, pUbicacion, pNombreRecibio, out pMensajeError);
        exito = true;
        pMensajeError = ??;
    }

    return exito;
}

I've never worked with out parameters in overriden methods, so I'm not sure how to declare the out parameter of the child method. I suppose that both out parameters (child and base) should be called the same way, but i'm not sure about this either.

Basically, I need to set pMensajeError in the child method with the same value returned by the out parameter of the base method. How should this work?


Solution

  • No, you don't need to set pMensajeError = ??;, at least not at the line where you put it. pMensajeError is already set by the call to base.AgregarEtapa. You can re-assign if you actually want to give it a different value, but if you want to use the value set by the base class implementation, you don't need to do anything special.

    The only thing you need to keep in mind is that your call to base.AgregarEtapa appears inside an if block. You need to think about what you want to do when the if condition is false, and base.AgregarEtapa never gets called.

    This could look something like this:

    if (seHace)
    { 
        base.AgregarEtapa(pFechaIngreso, pEtapa, pUbicacion, pNombreRecibio, out pMensajeError);
        exito = true;
    }
    else
    {
        pMensajeError = ??;
    }
    
    return exito;