0

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'
masroore
  • 9,668
  • 3
  • 23
  • 28
  • 1
    `TheType` is a name of property, it's not name of some class you are instanitating – Sergey Berezovskiy May 10 '15 at 10:10
  • While @Lukazoids answer is correct, keep in mind that this way is probably providing the weekest guarantee in terms of (static) safety. Depending on your usecase a combination of generic baseclass, factory children, common interface for created instance, ... might improve overall quality. Do you mind providing more details? – CaringDev May 11 '15 at 07:51

1 Answers1

4

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.

Lukazoid
  • 19,016
  • 3
  • 62
  • 85