Search code examples
c#typesreturnparent

C# child class returning a unknown type (futher: from parent)


i have interface:

public interface Inx<T>
{
   T Set(Data data);
}

simple class with this metod

public class Base
{
   ??? Set(Data data) { ... }
}

and parent class like that:

public class Parent : Base, Inx<Parent>
{
   ...
}

i want to return Parent type from Set metod in child class It's possible ? I need it do to something like that:

list.Add(new Parent().Set(data));

Now i have to do that:

T t = new T();
t.Set(data);
list.Add(t);

And its little annoying, i have to use it many time


Sorry for spaming well hmm i can use something like that:

this.GetType().GetConstructor(new System.Type[] { typeof(Data) }).Invoke(new object[] { data })

so maybe good soluction is return a object from this method ;\ ?

well generic class with generic interface seem's be big memory waste ... beacose function of this class are same only return type is diffrent


Solution

  • Is this what you want?

    interface Inx<T> { 
        T Set(Data data);
    }
    public class Base
    {
        public virtual T Set<T>(Data data)
        {
            T t = default(T);
            return t;
        }
    }
    public class Parent : Base, Inx<Parent>
    {
        public Parent Set(Data data)
        {
            return base.Set<Parent>(data);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var data = new Data();
            var list = new List<Parent>();
            list.Add(new Parent().Set<Parent>(data));
            // or 
            list.Add(new Parent().Set(data));
        }
    }
    

    EDIT: It's better to move the interface implementation up to the Base class as Marc said:

    interface Inx<T> { 
        T Set(Data data);
    }
    public class Base<T> : Inx<T>
    {
        public virtual T Set(Data data)
        {
            T t = default(T);
            return t;
        }
    }
    public class Parent : Base<Parent>
    {        
    }
    class Program
    {
        static void Main(string[] args)
        {
            var data = new Data();
            var list = new List<Parent>();
            list.Add(new Parent().Set(data));            
        }
    }