Question

I am stuck with this simple looking code for over an hour now... I have few classes...and methods like this:

abstract class ClassBase<SampleInterface> {//Some methods};

public class ClassAction1: ClassBase<MyInterface> {//Some methods};

public class ClassAction2: ClassBase<MyInterface> {//Some methods};

class SomeClass
{ 
    public void AddClassRange(ICollection<ClassBase<MyInterface>> range)
    {
        foreach (ClassBase<MyInterface> ClassBase in range)
            AddClass(ClassBase);
    }


    public void AddClass(ClassBase<MyInterface> behavior)
    {
        // Something
    }
}

Now, I am trying to use these codes in a different class:

var arg1 = new ClassAction1 {//Something};
var arg2 = new ClassAction2 {//Something};

//try1
sampleElement.AddClassRange(new [] { arg1 });   // works fine

//try2
sampleElement.AddClassRange(new [] { arg2 });   // works fine

I want to combine try1 and try2:

// Something like this (try3)
sampleElement.AddClassRange(new [] { arg1, arg2 });   // Error
Error : No best type found for implicitly typed array

As I think, In try1 and try2 runtime is deciding the type for keyword new based on the parameter passed to it. But in try3, parameters are of different types and runtime fails to decide for the best type for the new keyword.

Thanks. Let me know if need more info.

Was it helpful?

Solution

Implicitly typed arrays only work when the type of the array element is the exact compile-time type of one of the elements. In other words, the compiler treats the set of element types as the set of candidate types, and then tries to find exactly one of those types to which all the other types can be implicitly converted.

In your case, the set of candidate types is ClassAction1 and ClassAction2, neither of which is implicitly convertible to the other - which is why you're getting a compiler error. So you need to state the desired element type explicitly - presumably ClassBase<MyInterface>:

sampleElement.AddClassRange(new ClassBase<MyInterface>[] { arg1, arg2 });

Alternatively, you can cast either or both of the elements:

sampleElement.AddClassRange(new[] { (ClassBase<MyInterface>) arg1, arg2 });

OTHER TIPS

just do:

sampleElement.AddClassRange
   (new [] { arg1 as ClassBase<MyInterface>,  arg2 as ClassBase<MyInterface>})

In fact, in one array you cannot have different object types. You should cast them to the same object type in your case because at last you have an object of type ClassBase<MyInterface> in your SomeClass, So you should cast it to ClassBase<MyInterface>. In your first sample this cast can be done implicitly but in your second sample it cannot.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top