We use a utility that generates code. I’d like to extend it and thought I might be able to do it without going back to the code generator. here is the problem.
The code generator gives me:
public abstract class BaseService
{
protected virtual SqlCommand CreateSelectCommand(string whereClause, Hashtable parameters, string orderClause, int maxRows);
protected DataSet Fill(SqlCommand command);
}
Then it generates lots of classes that implement this class. e.g.
public class ChildService : BaseService
{
protected override SqlCommand CreateSelectCommand(string whereClause, Hashtable parameters, string orderClause, int maxRows)
{
//implementation here
}
protected override SqlCommand CreateSelectCommand(string whereClause, Hashtable parameters, string orderClause, int maxRows)
{
//implementation here
}
public virtual DataSet Select(string whereClause, System.Collections.Hashtable parameters, string orderClause, int maxRows)
{
SqlCommand command = CreateSelectCommand(whereClause, parameters, orderClause, maxRows);
return Fill(command);
}
}
Now I want to extend all the child classes to give me an override of the Select method. I tried an extension method something like this:
public DataSet Select(this BaseService service, string whereClause, Hashtable parameters, string orderBy, int startRowIndex, int maximumRows)
{
SqlCommand command = service.CreateSelectCommand(whereClause, parameters, orderClause, maxRows);
//Modify the command here
return service.Fill(command);
}
But the compiler complains because the service parameter is not an instance of the child class and so cannot access the protected CreateSelectCommand and Fill methods.
Is there any way around this so that I don’t have to implement this in every child class?
No, there isn’t.
Extension methods are static methods on static classes that only appear (through the magic of intellisense) to “belong” to a type. This means that types need to match exactly (for one).
It also means that they do not belong to the type and don’t have access to any protected/private members declared in the type.