1

I have the following classes:

public Employee : IPerson
{
  public string Name { get; set; }
}

public Manager : IPerson
{
  public string Name { get; set; }
}

at run-time, I may need to:

var person = new Manager();

or possibly:

var person = new Employee();

and then:

string name = person.Name;

at some point. I'm currently using Activator.CreateInstance(), but was wonder if approaching the problem incorrectly? The type of class is dictated at run-time so I have no advanced noticed.

I was hoping to avoid something like:

string externalValue;
var person;

switch (externalValue)
{
  case "Manager":
    person = new Manager();
    break;
  case "Employee":
    person = new Employee();
    break;
}
Carl Sagan
  • 982
  • 1
  • 13
  • 34
  • The question is still not clear for me. Are you trying to avoid the switch? or the magic strings? or you want to avoid instantiating with 'new' keyword? – kaptan Feb 05 '14 at 00:43
  • I'm trying to avoid all of the above, actually. – Carl Sagan Feb 05 '14 at 00:59

2 Answers2

1

You could use Dictionary<string, Func<IPerson>>, initialize it once and then use to create proper instance:

private Dictionary<string, Func<IPerson>> _initializers = new Dictionary<string, Func<IPerson>>() {
    { "Manager", () => new Manager() },
    { "Employee", () => new Employee() }
}
string externalValue;
var person = _initializers[externalValue]();
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • 1
    OP is trying to avoid magic strings. This moves the magic string from a switch to a dictionary key. – Eric J. Feb 05 '14 at 01:19
1

It looks like you are trying to create Dependency Injection (DI) system.

Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time

http://en.wikipedia.org/wiki/Dependency_injection

Rather than re-invent the wheel, I would suggest you look at existing DI systems. For a good overview, have a look at

How do the major C# DI/IoC frameworks compare?

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553