0

I am trying to construct an object with Activator.CreateInstance(), however i am receiving null for some unknown to me reason.

public class SpawnManager
{

    public void CreateSpawnable<T>()
    {
        Type type = typeof(T);

        ISpawnable<SpawnableParameters> spawnable = Activator.CreateInstance(type) as ISpawnable<SpawnableParameters>;

        // the spawnable object always returns null
    }

    public void Start()
    {
        CreateSpawnable<SpawnableCollectible>();
    }

}


public class SpawnableCollectible : ISpawnable<ParametersCollectible>
{

    public void Spawn(ParametersCollectible parameters)
    {
    }

}

Can somebody explain why i can't create an object instance which implements the given interface like that and write the correct approach for instantiating such an object?

3
  • You can find such mistakes yourself by using the debugger to look at the runtime values of all computations involved. See the answer. Commented Jan 5, 2015 at 11:03
  • Where is definition of SpawnableParameters? Commented Jan 5, 2015 at 11:05
  • public abstract class SpawnableParameters { } Commented Jan 5, 2015 at 11:06

2 Answers 2

7

Your types do not match. SpawnableCollectible implements ISpawnable<ParametersCollectible> not ISpawnable<SpawnableParameters> so the cast fails and as operator returns null.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. So how should I correctly approach this certain scenario?
implement the correct interface in your type. Or, cast it to correct type.
Casting to the correct type: var spawnable = (T)Activator.CreateInstance(type);
1

To add to what Selman22 said:

You'll probably want to constrain T to be a type that derives from ISpawnable<SpawnableParameters>. This will fix your problem:

public void CreateSpawnable<T>() where T: ISpawnable<SpawnableParameters>
{
    //...
}

This way, the client code cannot invoke your method with an invalid type T, and the as cast will always succeed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.