Skip to content

Instantly share code, notes, and snippets.

@tombuildsstuff
Created October 28, 2012 17:19
Show Gist options
  • Save tombuildsstuff/3969190 to your computer and use it in GitHub Desktop.
Save tombuildsstuff/3969190 to your computer and use it in GitHub Desktop.
.NET Casting Issue
public abstract class Base
{
// ..
}
public class Impl1 : Base
{
// ..
}
public class Impl2 : Base
{
// ..
}
public class Builder
{
private readonly IEnumerable<Base> _types;
public Builder(IEnumerable<Base> types)
{
_types = types;
}
public void DoStuff(dynamic instance, string typeName)
{
var type = _types.FirstOrDefault(t => t.Name.Equals(typeName));
var castableType = type.GetType();
// is there any way to cast to the type provided in castableType?
var castedObject = (castableType)instance;
}
}
@tombuildsstuff
Copy link
Author

Probably worth noting.. Types are injected using DI

Thanks for helping :)

@cargowire
Copy link

Did you end up using System.Convert.ChangeType?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment