masroore
masroore

Reputation: 10144

Using Activator.CreateInstance() with properties

I have the following property in a base (abstract) class:

protected abstract Type TheType { get; }

The above property is instantiated by child classes:

protected override Type TheType
{
  get { return typeof (ChildClass); }
}

I'd like to instantiate the object in the base class:

var obj = (TheType) Activator.CreateInstance<TheType>();

Unfortunately, I get the following compilation error:

Error   1   'BaseClass.TheType' is a 'property' but is used like a 'type'

How may I invoke Activator.CreateInstance() in this scenario?

PS: I've tried changing the property to a field:

protected Type TheType;

Still I get compilation error:

'BaseClass.TheType' is a 'field' but is used like a 'type'

Upvotes: 0

Views: 1303

Answers (1)

Lukazoid
Lukazoid

Reputation: 19426

TheType is a property which returns returns a Type, it is not a Type itself.

Use the Activator.CreateInstance(Type) method instead of the Activator.CreateInstance<T>() method, i.e.

var obj = Activator.CreateInstance(TheType);

Because you do not know which Type TheType will return, you will be unable to cast it to a specific type at runtime.

Upvotes: 4

Related Questions