osmo
osmo

Reputation: 87

C# Abstract methods with abstract parameters

Hi i'm trying to implement a structure where by I need to be able to create an abstract method in an abstract class in C#, which has an abstract object as a parameter.. example-

public abstract class AbstractMapper
{
     protected abstract AbstractObject doLoad(AbstractObject obj);
}

public abstract class UserMapper
{
     protected override User doLoad(User obj)
     {

     } 
}

In this example the "User" class extends the "AbstractObject" class... This is giving me errors on compile. Can someone advise on how i should achieve the above?

Upvotes: 0

Views: 2842

Answers (2)

Timothy Shields
Timothy Shields

Reputation: 79441

Use a generic type parameter on AbstractMapper constrained to be a subtype of AbstractObject:

public abstract class AbstractMapper<T> where T : AbstractObject
{
     protected abstract T doLoad(T obj);
}

public class UserMapper : AbstractMapper<User>
{
     protected override User doLoad(User obj)
     {
         ...
     } 
}

Upvotes: 5

Francisco Goldenstein
Francisco Goldenstein

Reputation: 13767

UserMapper is extending Object class and you are trying to override a method that doens't exist (doLoad).

Also, the signature of the method has a return type of User and you are not returning anything.

If you want User class to extend AbstractObject class, then do this:

public class User : AbstractObject 
{
      protected AbstractObject doLoad(AbstractObject obj)
      {
            // do something here and return an instance of a class that extends Abstract object
            return null; // added to make it compile
      }
}

Do you know that the access modifier protected means that it is only visible inside the class and in child classes? Read this: https://msdn.microsoft.com/en-us/library/wxh6fsc7.aspx

Upvotes: 1

Related Questions