napfernandes
napfernandes

Reputation: 1359

Extension Methods - How to return the correct type in inheritance?

I'm trying to create a generic methods from my Repository classes. The idea is a method that do something and return the instance of the class who called it.

public class BaseRepository { }

public class FooRepository : BaseRepository { }

public class BarRepository : BaseRepository { }

public static class ExtensionRepository
{
    public static BaseRepository AddParameter(this BaseRepository self, string parameterValue)
    {
        //...
        return self;
    }
}

// Calling the test:
FooRepository fooRepository = new FooRepository();
BaseRepository fooWrongInstance = fooRepository.AddParameter("foo");

BarRepository barRepository = new BarRepository();
BaseRepository barWrongInstance = barRepository.AddParameter("bar");

Well, this way I can get BaseRepository instance. But I need to get FooRepository and BarRepository instances, who called this method. Any idea? Thank you so much!!!

Upvotes: 4

Views: 408

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61912

Why do you want to return self in the first place? As far as I can see (don't know what's inside your method body) you don't assign a new object to self. So it's the same instance you're returning as the caller already has.

Maybe you could make it return void:

public static void AddParameter(this BaseRepository self, string parameterValue)
{
    //...
}

Usage:

FooRepository fooRepository = new FooRepository();
fooRepository.AddParameter("foo");
// fooRepository is still fooRepository after the call


BarRepository barRepository = new BarRepository();
barRepository.AddParameter("bar");
// barRepository is still barRepository after the call

Upvotes: 0

alex
alex

Reputation: 12654

You can try using generics

public static class ExtensionRepository
{
    public static T AddParameter<T>(this T self, string parameterValue) where T:BaseRepository 
    {
        //...
        return self;
    }
}

Upvotes: 7

Related Questions