Search code examples
c#interfacevirtual

Calling interface method C#


I am developing an ASP.net MVC application and I have a controller ExceptionController for displaying exceptions caught in my application.

This controller implements an interface IExceptionLogger

public class ExceptionController : Controller, IExceptionLogger
  {...}

which has one method void LogException(ExceptionDetail exceptionDetail);

I have implemented the method inside the ExceptionController too.

void IExceptionLogger.LogException(ExceptionDetail exceptionDetail)
 {...}

Now I need to call the method LogException() from the action Index of the ExceptionController.

public ActionResult Index(ExceptionDetail exceptionDetail)
    {
      // Method must be called here
      return View(exceptionDetail);
    }

How can I do this?


Solution

  • Because LogException is implemented explicitly, you have to cast to IExceptionLogger before calling it:

    public ActionResult Index(ExceptionDetail exceptionDetail)
    {
        ((IExceptionLogger)exceptionDetail).LogException();
    
         return View(exceptionDetail);
    }
    

    To make it work without casting, implement method implicitly:

    void LogException(ExceptionDetail exceptionDetail)
    {
    }