reza
reza

Reputation: 1379

How to pass a derived class to a base class function and return the derived class c#

I'm not sure if this is possible, but if it is not, what's the best/most elegant way to do this.

I have a List<DerivedClass> and I want to pull an element from the list that matches some criterion from it's BaseClass.

public class BaseClass {...}
public class DerivedClass : BaseClass {...}

List<DerivedClass> dcList = new List<DerivedClass>();
..
DerivedClass dc = GetTheOneWeWant(dcList)

where the function looks like this

public BaseClass GetTheOneWeWant(List<BaseClass> bc) {
  return bc[0]; //for example
}

So that that function can apply to all derived classes.

I tried something like this

    public T GetClosest<T>(List<T> list) {
        return list.Aggregate((c, d) => c.DistanceFrom(FrameCenterX, FrameCenterY) < d.DistanceFrom(FrameCenterX, FrameCenterY) ? c : d);
    }

but T doesn't know about method DistanceFrom(), and it will not let me cast T as a BaseClass. I'm not sure the best way to handle this. I could cast DerivedClass to BaseClass and send it to the function, but I want it to return the DerivedClass, not the BaseClass.

Upvotes: 1

Views: 73

Answers (2)

C Bauer
C Bauer

Reputation: 5103

Make the property/field/method you're using to determine if the "OneYouWant" public so that you can see it in derived class.

ex:

class Base {
    public bool MyProperty {get;set;}
}
class Derived : Base {

}
main.cs {
    var derivedList = //a List<Derived>()
    var whatIWanted = derivedList.Where(d => d.MyProperty);
}

Edit: Meant public

If you don't want to expose the property/field/method, then make that property protected and make a method that can get to it internally but perform the validation you need.

ex:

class Base {
    protected bool MyProperty {get;set;}
}
class Derived : Base {
    public bool IsWhatIWant() {
         return MyProperty;
    }
}
main.cs {
    var derivedList = //a List<Derived>()
    var whatIWanted = derivedList.Where(d => d.IsWhatIWant());
}

Upvotes: 0

SLaks
SLaks

Reputation: 888167

You're looking for generic constraints:

public T GetClosest<T>(List<T> list) where T : BaseClass {

Upvotes: 2

Related Questions