pend
pend

Reputation: 23

Why am I getting an "InvalidCastException: Specified cast is not valid." when trying to cast a Type to interface

I have a public class Typewriter with an interface IDialogueAnimation. In a method in the class DialoguePrinter I get all objects with the interface IDialogueAnimation. They come as Types and I want to cast them to IDialogueAnimation. However, it won't let me and I'm getting an "InvalidCastException: Specified cast is not valid." error. Why is this? Thanks!

I've checked that Typewriter and IDialogueAnimation are in the same assembly (which is something that has come up when I've tried to search for a solution).

IDialogueAnimation GetAnimationInterfaceFormName(string name)
{
    Type parentType = typeof(IDialogueAnimation);
    Assembly assembly = Assembly.GetExecutingAssembly();
    Type[] types = assembly.GetTypes();
    IEnumerable<Type> imp = types.Where(t => t.GetInterfaces().Contains(parentType));

    foreach (var item in imp)
    {
        if (item.Name.ToLower() == name.ToLower())
        {
            return (IDialogueAnimation) item;
        }
    }

    Debug.LogError("Can't find any animation with name " + name);
    return null;
}

This is the Interface

public interface IDialogueAnimation
{

    bool IsPlaying { get; set; }

    IEnumerator Run(OrderedDictionary wordGroup, float speed);

}

Upvotes: 0

Views: 2272

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40878

Your item variable is of type Type. You can't cast a Type to your interface because the class Type doesn't implement your interface.

You can only cast an instance of a type that implements your interface to the interface, not the Type itself.

If you want to return a new instance of that type, you can use Activator.CreateInstance() to do that:

if (item.Name.ToLower() == name.ToLower()) {
    return (IDialogueAnimation) Activator.CreateInstance(item);
}

If the type's constructor requires parameters, then you need to pass the parameters for the constructor as well. Something like:

return (IDialogueAnimation) Activator.CreateInstance(item, something, something);

Upvotes: 4

Related Questions