I'm trying to implement some generic method for an abstract class as follows :
public abstract class MyAbstractClass : MyBaseObject {
public MyAbstractClass() : base() { } // there is a parameterless constructor...
}
public class MyList<T> where T : MyBaseObject, new() {
// a generic container that is designed for the base class
}
//--- some paint control of mine
public class PaintControl : IDisposable {
public void InitDrawItems(MyList<MyAbstractClass> items) {
// paint items => this is where the compilation error occurs...
}
}
I get the following compilation error :
Error 24 'MyAbstractClass' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'MyList'
Of course, I'd like to use the abstract MyAbstractClass class (which has several children to handle painting accordingly).
Is there a way around this?
EDIT: I did make the class Abstract to make absolutely sure the children actually DO implement the abstract methods.
new() doesn't allow abstract classes and interfaces to be used as T, because they are not instantiable. new() means the generic type must declare a public parameterless constructor eligible for instantiation of an object.
So you have one option, in my opinion:
remove the new() clause, if you are ok with any abstract type derived from MyBaseObject being used with your generic. As your class is indeed abstract and a child of MyBaseObject, that would work just fine.
This is problem is caused by generic type variance. Declaring a concrete type actually creates a new type at compile time. The type parameters in a class can't be converted implicitly between types. There's no inheritance relation between MyList<MyBaseObject> and MyList<MyConcreteObject>.
Conversions are only permitted for generic interfaces or delegates.
There are two ways to fix this - use an interface instead of a concrete class, eg :
class MyList<T>:IList<T> where T : MyBaseObject, new()
{
}
class PaintControl {
public void InitDrawItems<T>(IList<MyAbstractClass> items) //where T:MyAbstractClass,new()
{
//var anItem=new T();
}
}
Or make InitDrawItems itself generic:
public void InitDrawItems<T>(MyList<T> items) where T:MyAbstractClass,new()
{
// No compilation errors here
}
You should remove the new() constraint for T type in MyList, since it's specifying that you can only use types that can be initialize - abstract ones can't.
You can check more details here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
The answer seems a bit of a workaround, but it actually makes lots of sense...
I know for sure which item of the list I am working with (I am looping through items). Since this item has been created, it is FOR SURE a non-abstract class. And hence, I can call the activator for that item, instead of new T() :
public void InitDrawItems(MyList<MyAbstractClass> items)
foreach (var item in items) {
Type type = o.GetType();
// type is definitely NOT abstract, since the object was created, so it is a
// non-abstract child class and I create the right "copy" of the item !
MyAbstractClass newItem = Activator.CreateInstance(type) as MyAbstractClass;
// ... do whatever I need with the item
}
}
NOTE: as for generics, it makes sens that calling new T() isn't allowed for abstract classes. Put it that way : a container of generic abstract items contains items of a derived child class since the abstract parent class cannot be instantiated. So calling new T() would definitely lead to an issue if allowed by the compiler : which child class should it be?!?
As #Martin pointed out in the comments, from the docs:
The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.
And the code you have written to define MyList<T>:
public class MyList<T> where T : MyBaseObject, new()
says MyList<T> is a generic class where T must have the new constraint (be type that you can instantiate).
So the reason of your compilation error on the code:
public void InitDrawItems(MyList<MyAbstractClass> items)
is because T in this case is MyAbstractClass which is an abstract class which cannot be instantiated.
So you options are as follows:
Make the method generic, like so:
public void InitDrawItems<T>(MyList<T> items) where T : MyAbstractClass, new()
{
// paint items => this is where the compilation error occurs...
}
Remove the new constraint from T in MyList
Make MyAbstractClass a normal class and not abstract.
It's very simple, you can't instantiate an abstract class and so T = MyAbstractClass clashes with the where T : new() constraint.
Related
I have two base classes BaseObject and BaseObjectSettings. The first defines the object behaviour and the second defines the state of the class (useful for serialisation).
If I want to create a derived BaseObject class with specific settings then I can use a method with a generic type constraint.
public void CreateBaseObjectInstance<T>(BaseObjectSettings baseObjectSettings) where T : BaseObject
{
var instance = pool.GetInstance<T>();
instance.Settings = baseObjectSettings;
scene.Add(instance);
}
The problem I am facing is that while I can constrain the generic type to BaseClass I can't constrain the BaseClassSettings to the relevant derived BaseClass. This means that I can do things like
CreateBaseObjectInstance<Banana>(new AppleSettings());
which seems a bit terrible.
What are my options given that I am currently constrained to both creating and initialising the object in the same method before adding it to the scene?
One way is to have all your settings classes inherit from a generic base class. The generic base class could then inherit from BaseObjectSettings. The generic type parameter indicates what kind of object this settings class is for.
For example, for your AppleSettings,
class AppleSettings: ObjectSettings<Apple> {
...
}
abstract class ObjectSettings<T>: BaseObjectSettings where T: BaseObject {}
Now, you can change CreateBaseObjectInstance to accept an instance of ObjectSettings<T> instead:
public void CreateBaseObjectInstance<T>(ObjectSettings<T> objectSettings) where T : BaseObject
{
var instance = pool.GetInstance<T>();
instance.Settings = objectSettings;
scene.Add(instance);
}
If you pass Banana as T, it would expect ObjectSettings<Banana>, preventing you from giving it AppleSettings, which is ObjectSettings<Apple>.
You need to create a generic interface or base class that where you define the settings type:
public class BaseObject<TSettings>
{
public TSettings Settings { get; set; }
}
Then your method will require two generic arguments - one for the actual object to create TObject and one for method's argument for the settings TSettings. You then constrain TObject to an implementation of the implemented interface or base class/derivation thereof, using generic argument TSettings as the constraint's type's generic argument
public void CreateBaseObjectInstance<TObject, TSettings>(
TSettings settings
)
where TObject : BaseObject<TSettings>
{
...
}
Example (using above BaseObject implementation):
public class MyObjectSettings
{
...
}
public class MyObject : BaseObject<MyObjectSettigns>
{
}
Method call:
var settings = new MyObjectSettings(){ ... };
CreateBaseObjectInstance<MyObject>( settings ); // second generic argument should be inferred
I don't really understand the logic here as things are missing, but from the code provided you can probably write:
public void CreateBaseObjectInstance<TBase, TSettings>(TSettings baseObjectSettings)
where TBase : BaseObject
where TSettings : BaseObjectSettings
Used like that:
CreateBaseObjectInstance<Banana, AppleSettings>(new AppleSettings());
Can be improved to:
public void CreateBaseObjectInstance<TBase, TSettings>(TSettings baseObjectSettings)
where TBase : BaseObject
where TSettings : BaseObjectSettings, new()
{
if ( baseObjectSettings == null ) baseObjectSettings = new TSettings();
...
}
CreateBaseObjectInstance<Banana, AppleSettings>();
But if there is a strong coupling between entity and settings, you should redesign to define dependency with an association using a thing that can also be similar to #Sweeper's and #Moho's answers:
Association, Composition and Aggregation in C#
Understanding the Aggregation, Association, Composition
Generics in .NET
Generic classes and methods
Item class
public class Item
{
public bool Check(int value) { ... }
}
Base abstract class with generic type constraint
public abstract class ClassBase<TItem>
where TItem : Item
{
protected IList<TItem> items;
public ClassBase(IEnumerable<TItem> items)
{
this.items = items.ToList();
}
public abstract bool CheckAll(int value);
}
Inherited class without constraints
public class MyClass<TItem> : ClassBase<TItem>
{
public override bool CheckAll(int value)
{
bool result = true;
foreach(TItem item in this.items)
{
if (!item.Check(value)) // this doesn't work
{
result = false;
break;
}
}
return result;
}
}
I would like to know why aren't generic type constraints inheritable? Because if my inherited class inherits from base class and passes over its generic type which has a constraint on the base class it automatically means that generic type in inherited class should have the same constraint without explicitly defining it. Shouldn't it?
Am I doing something wrong, understanding it wrong or is it really that generic type constraint aren't inheritable? If the latter is true, why in the world is that?
A bit of additional explanation
Why do I think that generic type constraints defined on a class should be inherited or enforced on child classes? Let me give you some additional code to make it bit less obvious.
Suppose that we have all three classes as per above. Then we also have this class:
public class DanteItem
{
public string ConvertHellLevel(int value) { ... }
}
As we can see this class does not inherit from Item so it can't be used as a concrete class as ClassBase<DanteItem> (forget the fact that ClassBase is abstract for now. It could as well be a regular class). Since MyClass doesn't define any constraints for its generic type it seems perfectly valid to have MyClass<DanteItem>...
But. This is why I think generic type constraints should be inherited/enforced on inherited classes just as with member generic type constraints because if we look at definition of MyClass it says:
MyClass<T> : ClassBase<T>
When T is DanteItem we can see that it automatically can't be used with MyClass because it's inherited from ClassBase<T> and DanteItem doesn't fulfill its generic type constraint. I could say that **generic type on MyClass depends on ClassBase generic type constraints because otherwise MyClass could be instantiated with any type. But we know it can't be.
It would be of course different when I would have MyClass defined as:
public class MyClass<T> : ClassBase<Item>
in this case T doesn't have anything to to with base class' generic type so it's independent from it.
This is all a bit long explanation/reasoning. I could simply sum it up by:
If we don't provide generic type constraint on MyClass it implicitly implies that we can instantiate MyClass with any concrete type. But we know that's not possible, since MyClass is inherited from ClassBase and that one has a generic type constraint.
I hope this makes much more sense now.
ANOTHER UPDATE:
This question was the subject of my blog in July 2013. Thanks for the great question!
UPDATE:
I've given this some more thought and I think the problem is that you don't want inheritance at all. Rather, what you want is for all constraints that must be placed on a type parameter in order for that type parameter to be used as a type argument in another type to be automatically deduced and invisibly added to the declaration of the type parameter. Yes?
Some simplified examples:
class B<T> where T:C {}
class D<U> : B<U> {}
U is a type parameter that is used in a context where it must be C. Therefore in your opinion the compiler should deduce that and automatically put a constraint of C on U.
What about this?
class B<T, U> where T : X where U : Y {}
class D<V> : B<V, V> {}
Now V is a type parameter used in a context where it must be both X and Y. Therefore in your opinion the compiler should deduce that and automatically put a constraint of X and Y on V. Yes?
What about this?
class B<T> where T : C<T> {}
class C<U> : B<D<U>> where U : IY<C<U>> {}
class D<V> : C<B<V>> where V : IZ<V> {}
I just made that up, but I assure you that it is a perfectly legal type hierarchy. Please describe a clear and consistent rule that does not go into infinite loops for determining what all the constraints are on T, U and V. Don't forget to handle the cases where type parameters are known to be reference types and the interface constraints have covariance or contravariance annotations! Also, the algorithm must have the property that it gives exactly the same results no matter what order B, C and D appear in source code.
If inference of constraints is the feature you want then the compiler has to be able to handle cases like this and give clear error messages when it cannot.
What is so special about base types? Why not actually implement the feature all the way?
class B<T> where T : X {}
class D<V> { B<V> bv; }
V is a type parameter used in a context where it must be convertible to X; therefore the compiler should deduce this fact and put a constraint of X on V. Yes? Or no?
Why are fields special? What about this:
class B<T> { static public void M<U>(ref U u) where U : T {} }
class D<V> : B<int> { static V v; static public void Q() { M(ref v); } }
V is a type parameter used in a context where it can only be int. Therefore the C# compiler should deduce this fact and automatically put a constraint of int on V.
Yes? No?
You see where this is going? Where does it stop? In order to implement your desired feature properly the compiler must do whole-program analysis.
The compiler does not do this level of analysis because that is putting the cart before the horse. When you construct a generic, you are required to prove to the compiler that you've satisfied the constraint. It's not the compiler's job to figure out what you meant to say and work out what further set of constraints satisfy the original constraint.
For similar reasons, the compiler also does not attempt to automatically infer variance annotations in interfaces on your behalf. See my article on that subject for details.
http://blogs.msdn.com/b/ericlippert/archive/2007/10/29/covariance-and-contravariance-in-c-part-seven-why-do-we-need-a-syntax-at-all.aspx
Original answer:
I would like to know why aren't generic type constraints inheritable?
Only members are inherited. A constraint is not a member.
if my inherited class inherits from base class and passes over its generic type which has a constraint on the base class it automatically means that generic type in inherited class should have the same constraint without explicitly defining it. Shouldn't it?
You're just asserting how something should be, without providing any explanation of why it should be that way. Explain to us why you believe that the world should be that way; what are the benefits and what are the drawbacks and what are the costs?
Am I doing something wrong, understanding it wrong or is it really that generic type constraint aren't inheritable?
Generic constraints are not inherited.
If the latter is true, why in the world is that?
Features are "not implemented" by default. We don't have to provide a reason why a feature is not implemented! Every feature is not implemented until someone spends the money to implement it.
Now, I hasten to note that generic type constraints are inherited on methods. Methods are members, members are inherited, and the constraint is a part of the method (though not part of its signature). So the constraint comes along with the method when it is inherited. When you say:
class B<T>
{
public virtual void M<U>() where U : T {}
}
class D<V> : B<IEnumerable<V>>
{
public override void M<U>() {}
}
Then D<V>.M<U> inherits the constraint and substitutes IEnumerable<V> for T; thus the constraint is that U must be convertible to IEnumerable<V>. Note that C# does not allow you to restate the constraint. This is in my opinion a misfeature; I would like to be able to restate the constraint for clarity.
But D does not inherit any kind of constraint on T from B; I don't understand how it possibly could. M is a member of B, and is inherited by D along with its constraint. But T is not a member of B in the first place, so what is there to inherit?
I'm really not understanding at all what feature it is that you want here. Can you explain with more details?
Below is a scenario where the implicit nature of this behavior causes different behavior than expected:
I recognize that this scenario may seem extravagant in the amount of setup, but this is just one example of where this behavior might cause a problem. Software applications can be complicated, so even though this scenario may seem complicated, I wouldn't say that this can't happen.
In this example there is an Operator class that implements two similar interfaces: IMonitor and IProcessor. Both have a start method and an IsStarted property, but the behavior for each interface within the Operator class is separate. I.e. there is a _MonitorStarted variable and a _ProcessorStarted variable within the Operator class.
MyClass<T> derives from ClassBase<T>. ClassBase has a type constraint on T that it must implement the IProcessor interface, and according to the suggested behavior MyClass inherits that type constraint.
MyClass<T> has a Check method, which is built with the assumption that it can get the value of the IProcessor.IsStarted property from the inner IProcessor object.
Suppose someone changes the implementation of ClassBase to remove the type constraint of IProcessor on the generic parameter T and replace it with a type contraint of IMonitor. This code will silently work, but will produce different behavior. The reason is because the Check method in MyClass<T> is now calling the IMonitor.IsStarted property instead of the IProcessor.IsStarted property, even though the code for MyClass<T> hasn't changed at all.
public interface IMonitor
{
void Start();
bool IsStarted { get; }
}
public interface IProcessor
{
void Start();
bool IsStarted { get; }
}
public class Operator : IMonitor, IProcessor
{
#region IMonitor Members
bool _MonitorStarted;
void IMonitor.Start()
{
Console.WriteLine("IMonitor.Start");
_MonitorStarted = true;
}
bool IMonitor.IsStarted
{
get { return _MonitorStarted; }
}
#endregion
#region IProcessor Members
bool _ProcessorStarted;
void IProcessor.Start()
{
Console.WriteLine("IProcessor.Start");
_ProcessorStarted = true;
}
bool IProcessor.IsStarted
{
get { return _ProcessorStarted; }
}
#endregion
}
public class ClassBase<T>
where T : IProcessor
{
protected T Inner { get; private set; }
public ClassBase(T inner)
{
this.Inner = inner;
}
public void Start()
{
this.Inner.Start();
}
}
public class MyClass<T> : ClassBase<T>
//where T : IProcessor
{
public MyClass(T inner) : base(inner) { }
public bool Check()
{
// this code was written assuming that it is calling IProcessor.IsStarted
return this.Inner.IsStarted;
}
}
public static class Extensions
{
public static void StartMonitoring(this IMonitor monitor)
{
monitor.Start();
}
public static void StartProcessing(this IProcessor processor)
{
processor.Start();
}
}
class Program
{
static void Main(string[] args)
{
var #operator = new Operator();
#operator.StartMonitoring();
var myClass = new MyClass<Operator>(#operator);
var result = myClass.Check();
// the value of result will be false if the type constraint on T in ClassBase<T> is where T : IProcessor
// the value of result will be true if the type constraint on T in ClassBase<T> is where T : IMonitor
}
}
I think you're confused becuase you're declaring you derived class with TItem as well.
If you think about it if you were using Q instead so.
public class MyClass<Q> : BaseClass<Q>
{
...
}
Then how is it to be determined that Q is of the type item?
You need to add the constraint to the derived classes Generic Type as well so
public class MyClass<Q> : BaseClass<Q> were Q : Item { ... }
Because the ClassBase has a constraint on his template (should by typeof Item), you have to add this constraint to MyClass too.
If you don't do this, you could create a new instance of MyClass, where the template isn't a type of Item. When creating the base class, it will fail.
[edit]
Hmm now a re-read your question, and I see your code does compile? Ok.
Well, im MyClass you don't know the basetype of this.items, so you can't call the Check method.
this.items is of the type IList, and in your class, TItem isn't specified, thats why the class doesn't understand the Check method.
Let me counter your question, why don't you want to add the constraint to your MyClass class? Given any other class type as template to this class, would result in an error. Why not prevent this errors by adding a constraint so it will fail compiletime.
I have 2 classes with the following declarations:
abstract class ClassBase<T, S> where T : myType where S : System.Data.Objects.DataClasses.EntityObject
abstract class ServiceBase<T> where T : myType
and I have 2 other classes, that inherit one from each, we can call ClassInherited and ServiceInherited. Note that the two Service classes are not in the same project as the other two.
The idea is that in the ServiceBase class I can declare a property like protected ClassBase<T,System.Data.Objects.DataClasses.EntityObject> Class { get; set; } and then in the inherited service`s constructor something like this.Class = ClassInheritedInstance
I already implemented the idea but it gives me this error when assigning the Class property in the ServiceInherited class constructor:
Cannot implicitly convert type 'ClassInherited' to 'ClassBase< T, S>'
Note that ClassInherited is indeed an specification of Class<T,S>... it's just that the compiler doesn't seem to be able to tell the types correctly. Also changing the declaration of the class property to protected ClassBase<T, EntityObjectInherited> works, and EntityObjectInherited is an implementation of System.Data.Objects.DataClasses.EntityObject... I don't see why is there a problem.
Update 1
Note that at compile time the type of ClassInherited is known, as its declaration is public class ClassInherited : ClassBase<myTypeInherited, EntityObjectInherited>
INITIAL ANSWER
The reason that you cannot use protected ClassBase<T,S> Class { get; set; } in the ServiceInherited-class is that you do not know the S-type that is needed to declare a type of the property Class.
You have to options:
Include the S type in the specification of the Service-type: abstract class ServiceBase<T, S> where T : myType where S : System.Data.Objects.DataClasses.EntityObject
Implement an interface for ClassBase with only the T-type, so that you can refer to a class-inherited-object without using the S-type. Then you CAN have a property in the service class (of the interface-type), since you do not need to specify the S-type.
Note that generic-type-checking is not checked at run-time, but at compile-time. Else it wouldn't be strong-typing.
UPDATE
The reason the cast won't work is that type ClassBase<T, EntityObjectInherited> is not equal or castable to ClassBase<T, System.Data.Objects.DataClasses.EntityObject>. Covariance doesn't work on class-types, only on interface-types.
I think the solution here is to work with interfaces. Use an interface for class-base, say IClassBase<T>. That way you can omit the S-type in the signature of the class, and only have it in the interface.
UPDATE (2)
One thing you can do is to create an interface for the Class property. You can define the following interface.
public interface IClass<T> where T : myType {
// TODO
// Define some interface definition, but you cannot use the
// EntityObject derived class, since they are not to be known
// in the service class.
}
If you implement this interface on your ClassBase class, and add a constructor on your ServiceBase class which accepts an object of type IClass, then you can push this object to property Class in the base-class. Like this:
public abstract class ClassBase<T, S> : IClass<T>
where T : MyType
where S : EntityObject {
}
public abstract class ServiceBase<T> where T : MyType {
protected ServiceBase(IClass<T> classObject) {
Class = classObject;
}
protected IClass<T> Class { get; set; }
}
public class ServiceInherited : ServiceBase<MyTypeDerived> {
public ServiceInherited(IClass<MyTypeDerived> classObject)
: base(classObject) {
}
}
One thing to note, is not to expose the S-type of the ClassBase to the interface. Since you do not want the Service-classes to know this type, they cannot actively call any methods or use properties that somehow have the S-type in their definition.
This ugly boxing, unboxing should work :
Class = (ClassBase<T, S>)(object)new ClassInherited();
Covariance is allowed only with generic interface today ?MSDN
This works :
// Covariance.
IEnumerable<string> strings = new List<string>();
// An object that is instantiated with a more derived type argument
// is assigned to an object instantiated with a less derived type argument.
// Assignment compatibility is preserved.
IEnumerable<object> objects = strings;
This doesn't :
List<string> strings = new List<string>();
List<object> objects = strings;
The compiler won't be able to guess that ClassInherited is indeed a correct match for ClassBase<T, S> as it does not know the exact types of T and S, that will be decided at generics type instanciation at runtime.
So if you're sure that at runtime the types will be compatible you can safely try a cast :
Class = ClassInheritedInstance as ClassBase<T, S>
This will only have a slight (not to say negligible) overhead as the CLR will need to check the compatibility of the types to have safe code.
Consider this generic class:
class TList<T> : System.Collections.Generic.List<T> {
}
I have another generic list class that contains these lists and may need to work on their members:
class TListList<U, T> : System.Collections.Generic.List<U> where U : TList<T>
{
public void Foo() {
foreach(U list in this) {
T bar = list[0];
}
}
}
And here's a concrete implementation:
class FooList : TList<Foo> {}
class FooListList : TListList<FooList, Foo> {}
What I'd like to do is drop the T type parameter in the specification of TListList and have the compiler notice it in the where clause and make it available to the members of TListList:
class TListList<U> where U : TList<T> { ...same Foo() as above... }
class FooList : TList<Foo> {}
class FooListList : TListList<FooList> {}
Is this possible and I'm just going about it the wrong way, or is the language just not capable of this?
No, this is not possible. Each distinct generic type must be declared ahead of time -- you can't omit T in the list <U, T>, because then T is an undeclared identifier.
(Also, I'm sure you know this, but inheriting from List<> is a very bad thing to do. Implement IList<> instead, and delegate to an implementation.)
I'm writing two APIs that I will use with many of my projects. Some projects my use one of the APIs, some the other, but the majority of my projects will use both. I'm trying to design them as if they're completely separate, but I'm struggling on one thing.
namespace FirstApi {
public abstract class MyBaseClass {
//constructor, some methods and properties
public IEnumerable<T> Search<T>() where T : MyBaseClass, new() {
//search logic here. must use generics as I create new instances of T here
}
}
}
namespace SecondApi {
public interface IMyInterface {
//some property and method signatures
IEnumerable<T> Search<T>() where T : IMyInterface, new();
}
}
namespace MyProject {
public class MyDerivedClass : MyBaseClass, IMyInterface {
}
}
Both APIs require this search method. The second API has some functionality in other classes that calls IMyInterface.Search<T>(), and I would like those classes that inherit MyBaseClass to use the Search<T> function defined in MyBaseClass.
Compilation error: The constraints for type parameter 'T' of method 'MyBaseClass.Search()' must match the constraints for type parameter 'T' of interface method 'IMyInterface.Search()'. Consider using an explicit interface implementation instead.
Note: When Search is called, T will always be the derived class of whichever abstract class or interface has been inherited. This was the only way I could find of achieving this in C# 2.0 (C# abstract class return derived type enumerator), and it's just caused more problems!
Is there a type-safe way that I can achieve this, without using objects and casting?
Solution:
Based on the accepted answer by Andras Zoltan, I created this class in my project, and will have to re-create this class for each project that uses both APIs.
public abstract class ApiAdapter<TAdapter> : MyBaseClass, IMyInterface where TAdapter: MyBaseClass, IJsonObject, new()
{
IEnumerable<T> IJsonObject.Search<T>()
{
foreach (TAdapter row in base.Search<TAdapter>())
yield return (T)(IMyInterface)row;
}
}
I then inherit this class like so.
public class Client : ApiAdapter<Client> {
//everything else can go here
}
You can explicitly implement the interfaces Search method, e.g.
public class MyDerivedClass : BasicTestApp.FirstApi.MyBaseClass, BasicTestApp.SecondApi.IMyInterface
{
IEnumerable<T> SecondApi.IMyInterface.Search<T>()
{
// do implementation
}
}
However, I think you are asking for the MyBaseClass Search method to be called when the part of the code that handles your object as IMyInterface calls the Search<T> method. I cannot see a way because you have two T types with different constraints that cannot be related.
If you did where T : BasicTestApp.FirstApi.MyBaseClass, IMyInterface, new(); in both definitions of the Search method then you would not have a problem but this would tie both your APIs together
Here is a possible implementation of your explicitly implemented interface method. It doesn't avoid the cast but at least keeps it neat.
IEnumerable<T> SecondApi.IMyInterface.Search<T>()
{
var results = base.Search<MyDerivedClass>();
return results.Cast<T>();
}
I started my answer with exposition on why it's not working for you, but I think that's well understood now so I'll leave it out.
I've upvoted #IndigoDelta's answer but it highlights something I don't like about the overall design here - I have a sneaking suspicion you should actually be using a generic interface and generic class; not generic methods because it doesn't make any sense that:
Note: When Search is called, T will always be the derived class of whichever abstract class or interface has been inherited.
I'm throwing this solution into the mix; which I think is better because it means that each derived type doesn't need to reimplement the IMyInterface.Search method, and it goes some way to actually enforcing this rule you mention. It's a generic type dedicated to join the two APIs together, meaning the derived types don't need to do anything:
namespace MyProject
{
using FirstApi;
using SecondApi;
public class SecondAPIAdapter<T2> : MyBaseClass, IMyInterface
where T2 : SecondAPIAdapter<T2>, new()
{
#region IMyInterface Members
IEnumerable<T> IMyInterface.Search<T>()
{
return Search<T2>().Cast<T>();
}
#endregion
}
//now you simply derive from the APIAdapter class - passing
//in your derived type as the generic parameter.
public class MyDerivedClass : SecondAPIAdapter<MyDerivedClass>
{ }
}
i think you can do explicit implementation of interface and when you will access methor thru IMyInterface.Search - compiler will run the right method.
You need to use an explicit implementation.
public class MyDerivedClass : MyBaseClass, IMyInterface
{
// The base class implementation of Search inherited
IEnumerable<T> IMyInterface.Search<T>()
{
// The interface implementation
throw new NotImplementedException();
// this would not work because base does not implement IMyInterface
return base.Search<T>();
}
}
Since the implementations are different this makes sense. If they are not different then either the base class should implement the interface and you should use covariance (.Net 4.0 only) to combine your contraints or, perhaps you don't need the interface at all.
I hope I'm not confused, could you not change your definitions, such that:
public interface IMyInterface<in T>
{
//some property and method signatures
IEnumerable<U> Search<U>() where U : T, new();
}
Providing a generic argument of T which can use to enforce that the implementation provides a search function constraint to types of T:
public abstract class MyBaseClass : IMyInterface<MyBaseClass>
{
public virtual IEnumerable<T> Search<T>() where T : MyBaseClass, new()
{
}
}
That way, your derived types are simply:
public class MyDerivedClass : MyBaseClass
{
}
Which you can then do searches as:
var derived = new MyDerivedClass();
IMyInterface<MyDerivedClass> iface = impl;
var results = iface.Search<MyDerivedClass>();