QldRobbo
QldRobbo

Reputation: 129

c# list of interface with generic items

My question is somewhat similar to Generic List of Generic Interfaces not allowed, any alternative approaches?

If I have an interface such as

public interface IPrimitive
{

}

public interface IPrimitive<T> : IPrimitive
{
     T Value { get; }
}

public class Star : IPrimitive<string> //must declare T here
{
    public string Value { get { return "foobar"; } }
}

public class Sun : IPrimitive<int>
{
    public int Value { get { return 0; } }
}

Then I have a list

var myList = new List<IPrimitive>();
myList.Add(new Star());
myList.Add(new Sun());

When looping through this list, how do I get the Value property?

foreach (var item in myList)
{
    var value = item.Value; // Value is not defined in IPrimitive so it doesn't know what it is
}

I'm not sure how this is possible.

Thanks, Rob

Upvotes: 3

Views: 4357

Answers (4)

cuongle
cuongle

Reputation: 75306

You can take advantage of dynamic:

foreach (dynamic item in myList) 
{ 
    var value = item.Value; 
} 

The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time

Upvotes: 4

Enigmativity
Enigmativity

Reputation: 117064

You could do something like this:

public interface IPrimitive
{
    object Value { get; }
}

public interface IPrimitive<T> : IPrimitive
{
    new T Value { get; }
}

public class Star : IPrimitive<string> //must declare T here
{
    public string Value { get { return "foobar"; } }
    object IPrimitive.Value { get { return this.Value; } }
}

public class Sun : IPrimitive<int>
{
    public int Value { get { return 0; } }
    object IPrimitive.Value { get { return this.Value; } }
}

You're then able to get the value out as an object when you only have IPrimitive.

Upvotes: 3

user854301
user854301

Reputation: 5493

You can move you Value property to base interface.

public interface IPrimitive
{
     object Value { get; }
}

How do you want to procced value in the loop it has different type?

Upvotes: 0

Keith Nicholas
Keith Nicholas

Reputation: 44298

of course not, your value is going to be of different types..... so you will have to downcast to the real type to get at the different values.

Basically your interface is failing. Its not "A common interface" It's more a "similar interface"

If you don't want to do casting, then you will have to find an interface which is common to both of them.

Upvotes: 2

Related Questions