I am having trouble with an abstract generic method.
Abstract Method Definition
protected abstract T InitEntity<T>(ref NpgsqlDataReader reader) where T : BaseEntity, new();
Implementation
protected override EUser InitEntity<EUser>(ref NpgsqlDataReader reader) {
I am having a problem with the EUser class in the override function. The function appears to treat EUser as the Generic T still where only BaseEntity functions are available. ERole is another class that implements BaseEntity and I am able to use the full functionality of that entity in the function. If I want to use EUser I have to type cast it to EUser every time I want to use a function that is not in it's parent BaseEntity. My goal was to pass the datareader to a child class and have it fill in the necessary information, but that is proving troublesome. I don't want to spend a lot of overhead type converting everything within the child class.
This is not the same as with generic classes. If I implement a child generic class I can specify EUser to the parent class and have full functionality of that entity still.
Has anyone else had a problem with this or am I implementing the abstract generic function incorrectly?
The parent function starts off like this:
protected T Select<T>(string sql, params NpgsqlParameter []) {
The parent class then calls the function like this:
T entity = InitEntity<T>(ref dr);
The problem has to be that T is used to generate the subclass method so even though the subclass method will only accept and use EUser. It still treats it as Generic T in the method. Do you guys have any suggestions?
This is all caused because I have a Parent class which has a couple of private fields that I don't want to share with any child classes. The generic method InitEntity uses some of those private fields. Because of this I am playing around with generic methods. I probably just need to rethink my implementation and settle with child generic classes.
Edit:
It looks like with Generic Methods in C# the variable type is defined when ever the function is called. You cannot seem to define that type further at the function level without major type conversion. If you try to implement the type in the sub class function as I did, everything will compile and function, but your type in the sub class will still be treated as what ever type was passed in. For my problem defined above I just need to change generic to be class level instead of just function. To make a abstract generic function. The child function needs to keep the generic T of what is being passed in, and then type convert it in the body of the function.