Simon
Simon

Reputation: 3285

C# Casting generics type to right type

I have this classes and interfaces:

public class XContainer
{
    public List<IXAttribute> Attributes { get; set; }
}

public interface IXAttribute
{
    string Name { get; set; }
}

public interface IXAttribute<T> : IXAttribute
{
    T Value { get; set; }
}

public class XAttribute<T> : IXAttribute<T>
{
    public T Value { get; set; }
}

I need to iterate over XContainer.Attributes and get property Value but I need to cast IXAttribute to correct generic representation like XAttribute<string> or XAttribute<int> but I don't want to use if-else if-else statement to check it like if XContainerl.Attributes[0] is XAttribute<string> then cast...

Is here a better way to do it?

Upvotes: 0

Views: 108

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112279

You could also define a generic extension method

public static class XAttributeExtensions
{
    public T GetValueOrDefault<T>(this IXAttribute attr)
    {        
        var typedAttr = attr as IXAttribute<T>;
        if (typedAttr == null) {
            return default(T);
        }
        return typedAttr.Value;
    }
}

Then you can call it with (assuming T is int)

int value = myAttr.GetValueOrDefault<int>();

The reason for implementing it as an extension method is that it will work with any implementation of the non generic interface IXAttribute.

Upvotes: 0

Diego Mijelshon
Diego Mijelshon

Reputation: 52745

There is a better way to do it.

Assuming you want to keep the current overall design, you could alter your non-generic interface and implementation as follows:

public interface IXAttribute
{
    string Name { get; set; }
    object GetValue();
}

public class XAttribute<T> : IXAttribute<T>
{
    public T Value { get; set; }

    public object GetValue()
    {
       return Value;
    }
}

Then your iterator would just access GetValue(), no casting needed.

That said, I think the design might not be the best for what you're doing.

Upvotes: 1

Related Questions