luke88
luke88

Reputation: 1008

c# inherits an Interface with a derivate class in a method's parameters

I have an abstract class like this:

public abstract class BaseClass
{
   ...
}

and then i have a lot of classes that derive from BaseClass:

public class DerivedOne : BaseClass
{
    ...
}

I need to implement an Interface that manage the possibility to implement a method that can uses alle the class derived from BaseClass like parameters:

public interface IErrorParser
{
    List<string> ParseErrorMessage(BaseClass base);
}

At this point, if i try to implement a class starting from the interface, in this way

public class FirstParser: IErrorParser
{
     public List<string> ParseErrorMessage(DerivedOne derived)
     {
        ...
     }
}

i receive the error:

FirstParser does not implement interface member 'IErrorParser.ParseErrorMessage(BaseClass)'

at this point i think that i need to use the generics... But i can't understand how...

Upvotes: 2

Views: 94

Answers (4)

Dbuggy
Dbuggy

Reputation: 911

If you define

public interface IErrorParser
{
    List<string> ParseErrorMessage(BaseClass base);
}

you can implement it in a class using DerivedClass like this

public class FirstParser: IErrorParser
{
     public List<string> ParseErrorMessage(BaseClass baseObj)
     {
        DerivedClass derived = (baseObj as DerivedClass);
        if (derived == null)
        {
           // handle null value
        }
        ...
     }
}

Edit base is a keyword and you should not use it as the name of an argument.

Upvotes: 0

Spawn
Spawn

Reputation: 935

You can create interface like

public interface IErrorParser<T> where T : BaseClass
{
    List<string> ParseErrorMessage(string defaultMessage, T service);
}

Upvotes: 0

Yacoub Massad
Yacoub Massad

Reputation: 27871

Make the IErrorParser interface generic like this:

public interface IErrorParser<T> where T:BaseClass 
{
    List<string> ParseErrorMessage(string defaultMessage, T service);
}

And then you can implement it like this:

public class FirstParser: IErrorParser<DerivedOne>
{
     public List<string> ParseErrorMessage(string defaultMessage, DerivedOne rerived)
     {
        ...
     }
}

Upvotes: 3

Nikolay Kostov
Nikolay Kostov

Reputation: 16983

This is because when you implement an interface you must exactly match all interface members (methods and properties) defined in it.

In your case you need to write

 public class FirstParser: IErrorParser
 {
      public List<string> ParseErrorMessage(string defaultMessage, BaseClass service);
      {
         ...
      }
 }

An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.

More info: https://msdn.microsoft.com/en-us/library/87d83y5b.aspx

Upvotes: 3

Related Questions