EDIT: changed Activator, still doesn’t work.
So I’m pretty (very) new to C# and I’m pretty sure this is a dupe, but I’ve looked through the previous questions and I still can’t work out all the points.
I am trying to reduce code smell by replacing some repeated code with a map over a generic list. Specifically, I have code that looks like
var fooNode = node as IFoo;
var barNode = node as IBar;
var bazNode = node as IBaz;
...
if(fooNode != null)
return new FooThing();
if(barNode != null)
return new BarThing();
if(bazNode != null)
return new BazThing();
...
and I want to generalise it.
Here’s my attempt:
var types = new Dictionary<Type, Type>
{
{typeof(IFoo), typeof(FooThing)},
{typeof(IBar), typeof(BarThing)},
...
}
foreach(var entry in types)
{
var castNode = node as entry.Key;
return Activator.CreateInstance(entry.Value);
}
Naturally, it doesn’t work: The type or namespace name 'entry' could not be found (are you missing a using directive or an assembly reference?). Can you help? Is this sort of thing even possible in C#?
How about this?
The problem is that you are confusing generic type parameters with runtime types and in particular the
Typeclass.If you know what a type will be at compile time then you can use the generic
Activator.CreateInstance<T>()method to create an instance of the underlying object – you can use things like type parameters so that this line of code doesn’t need to know what the type is, for example:However this just passes the buck. In order to call this method the value of the type parameter
Tmust be supplied somewhere – either way the compiler must be able to resolveTto a type (rather than a variable or method).Conversely the
Typeclass encodes type information at runtime such as its name or the assembly that a type is declared in.Activator.CreateInstancealso comes with an overload that allows you to supply an instance ofType:In your case it looks like you don’t know what the types will be at compile time, so you will be mostly working with the
Typeclass – you can usetypeof(MyClass)to get an instance of the the correspondingTypefor a class known at runtime, andmyObject.GetType()to get type information for an object at runtime.