CreateInstance InvalidCastException












0















There are three builds in my .net core application.



Solution.Models.Customer:



public class Customer : ICustomer
{
public void Get()
{
Console.WriteLine("Message!");
}
}


Solution.Interfaces.ICustomer:



public interface ICustomer
{
void Get();
}


Solution.Creator.ContainerCreator:



public class ContainerCreator
{
Assembly _assembly;

public void Add(Assembly assembly)
{
_assembly = assembly;
}

public object CreateInstance(Type type)
{
object instance;

var classesInfo = GetClassesInfo();
//classes Info looks for a match in the assembly with the passed parameter.
var result = classesInfo.Where(w => w.ClassType.FullName == type.FullName).FirstOrDefault();

var objectType = result.ClassType;

instance = Activator.CreateInstance(objectType);

return instance;
}
}


Then, when I create an object with the (ICustomer) type, it is successfully created, but if I cast to the (Customer) type, then an exception occurs - System.InvalidCastException.



var files = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"Solution.Models.dll",
SearchOption.TopDirectoryOnly);

var asm = Assembly.LoadFile(files[0]);

ContainerCreator containerCreator = new ContainerCreator();

containerCreator.Add(asm);
// Success
Customer = (ICustomer)containerCreator.CreateInstance(typeof(Customer));
// System.InvalidCastException
//Customer = (Customer)containerCreator.CreateInstance(typeof(Customer));


What am I doing wrong and how can I defeat this exception?










share|improve this question























  • If Customer and ICustomer are defined in different assemblies: are you sure all the loaded assemblies match? You can check this e.g. in the debugger in the Modules window.

    – Klaus Gütter
    Nov 19 '18 at 17:21













  • Your program that is calling CreateInstance knows the Customer type already from somewhere (otherwise you could not use this type in your source code there). Most likely the origin of that Customer type is not the Solution.Models.dll itself. Thus, you would have two different Customer types that are not convertible between each other (one from your program, one from your Solution.Models.dll)

    – elgonzo
    Nov 19 '18 at 17:21













  • Since your program already knows the type Customer -- it has to, otherwise the complier would complain about not knowing Customer when trying to compile Customer = (ICustomer)containerCreator.CreateInstance(typeof(Customer)); --, why do you go through all the hoopla with ContainerCreator and trying to load the assembly instead of just doing new Customer()? Your approach, as presented here, doesn't really make much sense...

    – elgonzo
    Nov 19 '18 at 17:26








  • 1





    Side note: What is this funky weirdness you do with Directory.GetFiles(...) there? Wouldn't it be much simpler to do var dllPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Solution.Models.dll")?

    – elgonzo
    Nov 19 '18 at 17:37








  • 1





    First, you should provide the full exception message of the InvalidCastException. Secondly, if you can do typeof(Customer), then that class Customer is already in scope, so why not do new Customer()? If you, just as @elgonzo suggests, have two unrelated classes both called Customer, you cannot create one with a reference to the Type object of the other, and you also cannot cast an instance of one of them to an interface implemented only by the other class.

    – Jeppe Stig Nielsen
    Nov 19 '18 at 17:37
















0















There are three builds in my .net core application.



Solution.Models.Customer:



public class Customer : ICustomer
{
public void Get()
{
Console.WriteLine("Message!");
}
}


Solution.Interfaces.ICustomer:



public interface ICustomer
{
void Get();
}


Solution.Creator.ContainerCreator:



public class ContainerCreator
{
Assembly _assembly;

public void Add(Assembly assembly)
{
_assembly = assembly;
}

public object CreateInstance(Type type)
{
object instance;

var classesInfo = GetClassesInfo();
//classes Info looks for a match in the assembly with the passed parameter.
var result = classesInfo.Where(w => w.ClassType.FullName == type.FullName).FirstOrDefault();

var objectType = result.ClassType;

instance = Activator.CreateInstance(objectType);

return instance;
}
}


Then, when I create an object with the (ICustomer) type, it is successfully created, but if I cast to the (Customer) type, then an exception occurs - System.InvalidCastException.



var files = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"Solution.Models.dll",
SearchOption.TopDirectoryOnly);

var asm = Assembly.LoadFile(files[0]);

ContainerCreator containerCreator = new ContainerCreator();

containerCreator.Add(asm);
// Success
Customer = (ICustomer)containerCreator.CreateInstance(typeof(Customer));
// System.InvalidCastException
//Customer = (Customer)containerCreator.CreateInstance(typeof(Customer));


What am I doing wrong and how can I defeat this exception?










share|improve this question























  • If Customer and ICustomer are defined in different assemblies: are you sure all the loaded assemblies match? You can check this e.g. in the debugger in the Modules window.

    – Klaus Gütter
    Nov 19 '18 at 17:21













  • Your program that is calling CreateInstance knows the Customer type already from somewhere (otherwise you could not use this type in your source code there). Most likely the origin of that Customer type is not the Solution.Models.dll itself. Thus, you would have two different Customer types that are not convertible between each other (one from your program, one from your Solution.Models.dll)

    – elgonzo
    Nov 19 '18 at 17:21













  • Since your program already knows the type Customer -- it has to, otherwise the complier would complain about not knowing Customer when trying to compile Customer = (ICustomer)containerCreator.CreateInstance(typeof(Customer)); --, why do you go through all the hoopla with ContainerCreator and trying to load the assembly instead of just doing new Customer()? Your approach, as presented here, doesn't really make much sense...

    – elgonzo
    Nov 19 '18 at 17:26








  • 1





    Side note: What is this funky weirdness you do with Directory.GetFiles(...) there? Wouldn't it be much simpler to do var dllPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Solution.Models.dll")?

    – elgonzo
    Nov 19 '18 at 17:37








  • 1





    First, you should provide the full exception message of the InvalidCastException. Secondly, if you can do typeof(Customer), then that class Customer is already in scope, so why not do new Customer()? If you, just as @elgonzo suggests, have two unrelated classes both called Customer, you cannot create one with a reference to the Type object of the other, and you also cannot cast an instance of one of them to an interface implemented only by the other class.

    – Jeppe Stig Nielsen
    Nov 19 '18 at 17:37














0












0








0








There are three builds in my .net core application.



Solution.Models.Customer:



public class Customer : ICustomer
{
public void Get()
{
Console.WriteLine("Message!");
}
}


Solution.Interfaces.ICustomer:



public interface ICustomer
{
void Get();
}


Solution.Creator.ContainerCreator:



public class ContainerCreator
{
Assembly _assembly;

public void Add(Assembly assembly)
{
_assembly = assembly;
}

public object CreateInstance(Type type)
{
object instance;

var classesInfo = GetClassesInfo();
//classes Info looks for a match in the assembly with the passed parameter.
var result = classesInfo.Where(w => w.ClassType.FullName == type.FullName).FirstOrDefault();

var objectType = result.ClassType;

instance = Activator.CreateInstance(objectType);

return instance;
}
}


Then, when I create an object with the (ICustomer) type, it is successfully created, but if I cast to the (Customer) type, then an exception occurs - System.InvalidCastException.



var files = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"Solution.Models.dll",
SearchOption.TopDirectoryOnly);

var asm = Assembly.LoadFile(files[0]);

ContainerCreator containerCreator = new ContainerCreator();

containerCreator.Add(asm);
// Success
Customer = (ICustomer)containerCreator.CreateInstance(typeof(Customer));
// System.InvalidCastException
//Customer = (Customer)containerCreator.CreateInstance(typeof(Customer));


What am I doing wrong and how can I defeat this exception?










share|improve this question














There are three builds in my .net core application.



Solution.Models.Customer:



public class Customer : ICustomer
{
public void Get()
{
Console.WriteLine("Message!");
}
}


Solution.Interfaces.ICustomer:



public interface ICustomer
{
void Get();
}


Solution.Creator.ContainerCreator:



public class ContainerCreator
{
Assembly _assembly;

public void Add(Assembly assembly)
{
_assembly = assembly;
}

public object CreateInstance(Type type)
{
object instance;

var classesInfo = GetClassesInfo();
//classes Info looks for a match in the assembly with the passed parameter.
var result = classesInfo.Where(w => w.ClassType.FullName == type.FullName).FirstOrDefault();

var objectType = result.ClassType;

instance = Activator.CreateInstance(objectType);

return instance;
}
}


Then, when I create an object with the (ICustomer) type, it is successfully created, but if I cast to the (Customer) type, then an exception occurs - System.InvalidCastException.



var files = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"Solution.Models.dll",
SearchOption.TopDirectoryOnly);

var asm = Assembly.LoadFile(files[0]);

ContainerCreator containerCreator = new ContainerCreator();

containerCreator.Add(asm);
// Success
Customer = (ICustomer)containerCreator.CreateInstance(typeof(Customer));
// System.InvalidCastException
//Customer = (Customer)containerCreator.CreateInstance(typeof(Customer));


What am I doing wrong and how can I defeat this exception?







c# reflection






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 19 '18 at 17:15









TibomsoTibomso

1139




1139













  • If Customer and ICustomer are defined in different assemblies: are you sure all the loaded assemblies match? You can check this e.g. in the debugger in the Modules window.

    – Klaus Gütter
    Nov 19 '18 at 17:21













  • Your program that is calling CreateInstance knows the Customer type already from somewhere (otherwise you could not use this type in your source code there). Most likely the origin of that Customer type is not the Solution.Models.dll itself. Thus, you would have two different Customer types that are not convertible between each other (one from your program, one from your Solution.Models.dll)

    – elgonzo
    Nov 19 '18 at 17:21













  • Since your program already knows the type Customer -- it has to, otherwise the complier would complain about not knowing Customer when trying to compile Customer = (ICustomer)containerCreator.CreateInstance(typeof(Customer)); --, why do you go through all the hoopla with ContainerCreator and trying to load the assembly instead of just doing new Customer()? Your approach, as presented here, doesn't really make much sense...

    – elgonzo
    Nov 19 '18 at 17:26








  • 1





    Side note: What is this funky weirdness you do with Directory.GetFiles(...) there? Wouldn't it be much simpler to do var dllPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Solution.Models.dll")?

    – elgonzo
    Nov 19 '18 at 17:37








  • 1





    First, you should provide the full exception message of the InvalidCastException. Secondly, if you can do typeof(Customer), then that class Customer is already in scope, so why not do new Customer()? If you, just as @elgonzo suggests, have two unrelated classes both called Customer, you cannot create one with a reference to the Type object of the other, and you also cannot cast an instance of one of them to an interface implemented only by the other class.

    – Jeppe Stig Nielsen
    Nov 19 '18 at 17:37



















  • If Customer and ICustomer are defined in different assemblies: are you sure all the loaded assemblies match? You can check this e.g. in the debugger in the Modules window.

    – Klaus Gütter
    Nov 19 '18 at 17:21













  • Your program that is calling CreateInstance knows the Customer type already from somewhere (otherwise you could not use this type in your source code there). Most likely the origin of that Customer type is not the Solution.Models.dll itself. Thus, you would have two different Customer types that are not convertible between each other (one from your program, one from your Solution.Models.dll)

    – elgonzo
    Nov 19 '18 at 17:21













  • Since your program already knows the type Customer -- it has to, otherwise the complier would complain about not knowing Customer when trying to compile Customer = (ICustomer)containerCreator.CreateInstance(typeof(Customer)); --, why do you go through all the hoopla with ContainerCreator and trying to load the assembly instead of just doing new Customer()? Your approach, as presented here, doesn't really make much sense...

    – elgonzo
    Nov 19 '18 at 17:26








  • 1





    Side note: What is this funky weirdness you do with Directory.GetFiles(...) there? Wouldn't it be much simpler to do var dllPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Solution.Models.dll")?

    – elgonzo
    Nov 19 '18 at 17:37








  • 1





    First, you should provide the full exception message of the InvalidCastException. Secondly, if you can do typeof(Customer), then that class Customer is already in scope, so why not do new Customer()? If you, just as @elgonzo suggests, have two unrelated classes both called Customer, you cannot create one with a reference to the Type object of the other, and you also cannot cast an instance of one of them to an interface implemented only by the other class.

    – Jeppe Stig Nielsen
    Nov 19 '18 at 17:37

















If Customer and ICustomer are defined in different assemblies: are you sure all the loaded assemblies match? You can check this e.g. in the debugger in the Modules window.

– Klaus Gütter
Nov 19 '18 at 17:21







If Customer and ICustomer are defined in different assemblies: are you sure all the loaded assemblies match? You can check this e.g. in the debugger in the Modules window.

– Klaus Gütter
Nov 19 '18 at 17:21















Your program that is calling CreateInstance knows the Customer type already from somewhere (otherwise you could not use this type in your source code there). Most likely the origin of that Customer type is not the Solution.Models.dll itself. Thus, you would have two different Customer types that are not convertible between each other (one from your program, one from your Solution.Models.dll)

– elgonzo
Nov 19 '18 at 17:21







Your program that is calling CreateInstance knows the Customer type already from somewhere (otherwise you could not use this type in your source code there). Most likely the origin of that Customer type is not the Solution.Models.dll itself. Thus, you would have two different Customer types that are not convertible between each other (one from your program, one from your Solution.Models.dll)

– elgonzo
Nov 19 '18 at 17:21















Since your program already knows the type Customer -- it has to, otherwise the complier would complain about not knowing Customer when trying to compile Customer = (ICustomer)containerCreator.CreateInstance(typeof(Customer)); --, why do you go through all the hoopla with ContainerCreator and trying to load the assembly instead of just doing new Customer()? Your approach, as presented here, doesn't really make much sense...

– elgonzo
Nov 19 '18 at 17:26







Since your program already knows the type Customer -- it has to, otherwise the complier would complain about not knowing Customer when trying to compile Customer = (ICustomer)containerCreator.CreateInstance(typeof(Customer)); --, why do you go through all the hoopla with ContainerCreator and trying to load the assembly instead of just doing new Customer()? Your approach, as presented here, doesn't really make much sense...

– elgonzo
Nov 19 '18 at 17:26






1




1





Side note: What is this funky weirdness you do with Directory.GetFiles(...) there? Wouldn't it be much simpler to do var dllPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Solution.Models.dll")?

– elgonzo
Nov 19 '18 at 17:37







Side note: What is this funky weirdness you do with Directory.GetFiles(...) there? Wouldn't it be much simpler to do var dllPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Solution.Models.dll")?

– elgonzo
Nov 19 '18 at 17:37






1




1





First, you should provide the full exception message of the InvalidCastException. Secondly, if you can do typeof(Customer), then that class Customer is already in scope, so why not do new Customer()? If you, just as @elgonzo suggests, have two unrelated classes both called Customer, you cannot create one with a reference to the Type object of the other, and you also cannot cast an instance of one of them to an interface implemented only by the other class.

– Jeppe Stig Nielsen
Nov 19 '18 at 17:37





First, you should provide the full exception message of the InvalidCastException. Secondly, if you can do typeof(Customer), then that class Customer is already in scope, so why not do new Customer()? If you, just as @elgonzo suggests, have two unrelated classes both called Customer, you cannot create one with a reference to the Type object of the other, and you also cannot cast an instance of one of them to an interface implemented only by the other class.

– Jeppe Stig Nielsen
Nov 19 '18 at 17:37












1 Answer
1






active

oldest

votes


















1














Note:I think OP is trying to create some kind of Plugin stuff. If so, there are many custom libraries for that I suggest you can use already implemented stuff, rather than creating the wheel by yourself



This is a pretty common mistake when people first start to play with assemblies during run time. Been there done that :) The problem is that you are using Assembly.LoadFile to load your assembly into your app-domain. Without going further into detail, even if you load the same dll using Assembly.LoadFile, types defined in the assembly will be treated as differently. Let us say I have assembly A



../MyFolder/A.dll
public class MyType;
public class MyAnotherType;
....

var aDll = Assembly.LoadFile("A.dll");
var aDllAgain = Assembly.LoadFile("A.dll");
var myTypeFromADll =aDll.GetType("MyType");
var myTypeFromADllAgain = aDllAgain.GetType("MyType");

//Yes this is of type MyType but since you used LoadFile
//It is of type MyType from a_dll code base
var instanceFromADll = Activator.CreateInstance(myTypeFromADll);

//Yes this is of type MyType but since you used LoadFile
//It is of type MyType from a_dll_again code base
var instanceFromADllAgain = Activator.CreateInstance(myTypeFromADllAgain);


So you are getting an InvalidCastException because you are trying to cast an instance of type X into type Y.



The solution is simple. You should use Assemly.Load method, and somehow if you can not next is Assembly.LoadFrom. Unless you know absolutely what you are doing, stay away from Assembly.LoadFile.



Here is a very good and detailed explanation. Best practices






share|improve this answer



















  • 1





    Thank you, you're right, it was Assembly.LoadFile

    – Tibomso
    Nov 20 '18 at 4:32











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53379645%2fcreateinstance-invalidcastexception%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














Note:I think OP is trying to create some kind of Plugin stuff. If so, there are many custom libraries for that I suggest you can use already implemented stuff, rather than creating the wheel by yourself



This is a pretty common mistake when people first start to play with assemblies during run time. Been there done that :) The problem is that you are using Assembly.LoadFile to load your assembly into your app-domain. Without going further into detail, even if you load the same dll using Assembly.LoadFile, types defined in the assembly will be treated as differently. Let us say I have assembly A



../MyFolder/A.dll
public class MyType;
public class MyAnotherType;
....

var aDll = Assembly.LoadFile("A.dll");
var aDllAgain = Assembly.LoadFile("A.dll");
var myTypeFromADll =aDll.GetType("MyType");
var myTypeFromADllAgain = aDllAgain.GetType("MyType");

//Yes this is of type MyType but since you used LoadFile
//It is of type MyType from a_dll code base
var instanceFromADll = Activator.CreateInstance(myTypeFromADll);

//Yes this is of type MyType but since you used LoadFile
//It is of type MyType from a_dll_again code base
var instanceFromADllAgain = Activator.CreateInstance(myTypeFromADllAgain);


So you are getting an InvalidCastException because you are trying to cast an instance of type X into type Y.



The solution is simple. You should use Assemly.Load method, and somehow if you can not next is Assembly.LoadFrom. Unless you know absolutely what you are doing, stay away from Assembly.LoadFile.



Here is a very good and detailed explanation. Best practices






share|improve this answer



















  • 1





    Thank you, you're right, it was Assembly.LoadFile

    – Tibomso
    Nov 20 '18 at 4:32
















1














Note:I think OP is trying to create some kind of Plugin stuff. If so, there are many custom libraries for that I suggest you can use already implemented stuff, rather than creating the wheel by yourself



This is a pretty common mistake when people first start to play with assemblies during run time. Been there done that :) The problem is that you are using Assembly.LoadFile to load your assembly into your app-domain. Without going further into detail, even if you load the same dll using Assembly.LoadFile, types defined in the assembly will be treated as differently. Let us say I have assembly A



../MyFolder/A.dll
public class MyType;
public class MyAnotherType;
....

var aDll = Assembly.LoadFile("A.dll");
var aDllAgain = Assembly.LoadFile("A.dll");
var myTypeFromADll =aDll.GetType("MyType");
var myTypeFromADllAgain = aDllAgain.GetType("MyType");

//Yes this is of type MyType but since you used LoadFile
//It is of type MyType from a_dll code base
var instanceFromADll = Activator.CreateInstance(myTypeFromADll);

//Yes this is of type MyType but since you used LoadFile
//It is of type MyType from a_dll_again code base
var instanceFromADllAgain = Activator.CreateInstance(myTypeFromADllAgain);


So you are getting an InvalidCastException because you are trying to cast an instance of type X into type Y.



The solution is simple. You should use Assemly.Load method, and somehow if you can not next is Assembly.LoadFrom. Unless you know absolutely what you are doing, stay away from Assembly.LoadFile.



Here is a very good and detailed explanation. Best practices






share|improve this answer



















  • 1





    Thank you, you're right, it was Assembly.LoadFile

    – Tibomso
    Nov 20 '18 at 4:32














1












1








1







Note:I think OP is trying to create some kind of Plugin stuff. If so, there are many custom libraries for that I suggest you can use already implemented stuff, rather than creating the wheel by yourself



This is a pretty common mistake when people first start to play with assemblies during run time. Been there done that :) The problem is that you are using Assembly.LoadFile to load your assembly into your app-domain. Without going further into detail, even if you load the same dll using Assembly.LoadFile, types defined in the assembly will be treated as differently. Let us say I have assembly A



../MyFolder/A.dll
public class MyType;
public class MyAnotherType;
....

var aDll = Assembly.LoadFile("A.dll");
var aDllAgain = Assembly.LoadFile("A.dll");
var myTypeFromADll =aDll.GetType("MyType");
var myTypeFromADllAgain = aDllAgain.GetType("MyType");

//Yes this is of type MyType but since you used LoadFile
//It is of type MyType from a_dll code base
var instanceFromADll = Activator.CreateInstance(myTypeFromADll);

//Yes this is of type MyType but since you used LoadFile
//It is of type MyType from a_dll_again code base
var instanceFromADllAgain = Activator.CreateInstance(myTypeFromADllAgain);


So you are getting an InvalidCastException because you are trying to cast an instance of type X into type Y.



The solution is simple. You should use Assemly.Load method, and somehow if you can not next is Assembly.LoadFrom. Unless you know absolutely what you are doing, stay away from Assembly.LoadFile.



Here is a very good and detailed explanation. Best practices






share|improve this answer













Note:I think OP is trying to create some kind of Plugin stuff. If so, there are many custom libraries for that I suggest you can use already implemented stuff, rather than creating the wheel by yourself



This is a pretty common mistake when people first start to play with assemblies during run time. Been there done that :) The problem is that you are using Assembly.LoadFile to load your assembly into your app-domain. Without going further into detail, even if you load the same dll using Assembly.LoadFile, types defined in the assembly will be treated as differently. Let us say I have assembly A



../MyFolder/A.dll
public class MyType;
public class MyAnotherType;
....

var aDll = Assembly.LoadFile("A.dll");
var aDllAgain = Assembly.LoadFile("A.dll");
var myTypeFromADll =aDll.GetType("MyType");
var myTypeFromADllAgain = aDllAgain.GetType("MyType");

//Yes this is of type MyType but since you used LoadFile
//It is of type MyType from a_dll code base
var instanceFromADll = Activator.CreateInstance(myTypeFromADll);

//Yes this is of type MyType but since you used LoadFile
//It is of type MyType from a_dll_again code base
var instanceFromADllAgain = Activator.CreateInstance(myTypeFromADllAgain);


So you are getting an InvalidCastException because you are trying to cast an instance of type X into type Y.



The solution is simple. You should use Assemly.Load method, and somehow if you can not next is Assembly.LoadFrom. Unless you know absolutely what you are doing, stay away from Assembly.LoadFile.



Here is a very good and detailed explanation. Best practices







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 20 '18 at 3:58









Hasan Emrah SüngüHasan Emrah Süngü

1,676319




1,676319








  • 1





    Thank you, you're right, it was Assembly.LoadFile

    – Tibomso
    Nov 20 '18 at 4:32














  • 1





    Thank you, you're right, it was Assembly.LoadFile

    – Tibomso
    Nov 20 '18 at 4:32








1




1





Thank you, you're right, it was Assembly.LoadFile

– Tibomso
Nov 20 '18 at 4:32





Thank you, you're right, it was Assembly.LoadFile

– Tibomso
Nov 20 '18 at 4:32




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53379645%2fcreateinstance-invalidcastexception%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

鏡平學校

ꓛꓣだゔៀៅຸ໢ທຮ໕໒ ,ໂ'໥໓າ໼ឨឲ៵៭ៈゎゔit''䖳𥁄卿' ☨₤₨こゎもょの;ꜹꟚꞖꞵꟅꞛေၦေɯ,ɨɡ𛃵𛁹ޝ޳ޠ޾,ޤޒޯ޾𫝒𫠁သ𛅤チョ'サノބޘދ𛁐ᶿᶇᶀᶋᶠ㨑㽹⻮ꧬ꧹؍۩وَؠ㇕㇃㇪ ㇦㇋㇋ṜẰᵡᴠ 軌ᵕ搜۳ٰޗޮ޷ސޯ𫖾𫅀ल, ꙭ꙰ꚅꙁꚊꞻꝔ꟠Ꝭㄤﺟޱސꧨꧼ꧴ꧯꧽ꧲ꧯ'⽹⽭⾁⿞⼳⽋២៩ញណើꩯꩤ꩸ꩮᶻᶺᶧᶂ𫳲𫪭𬸄𫵰𬖩𬫣𬊉ၲ𛅬㕦䬺𫝌𫝼,,𫟖𫞽ហៅ஫㆔ాఆఅꙒꚞꙍ,Ꙟ꙱エ ,ポテ,フࢰࢯ𫟠𫞶 𫝤𫟠ﺕﹱﻜﻣ𪵕𪭸𪻆𪾩𫔷ġ,ŧآꞪ꟥,ꞔꝻ♚☹⛵𛀌ꬷꭞȄƁƪƬșƦǙǗdžƝǯǧⱦⱰꓕꓢႋ神 ဴ၀க௭எ௫ឫោ ' េㇷㇴㇼ神ㇸㇲㇽㇴㇼㇻㇸ'ㇸㇿㇸㇹㇰㆣꓚꓤ₡₧ ㄨㄟ㄂ㄖㄎ໗ツڒذ₶।ऩछएोञयूटक़कयँृी,冬'𛅢𛅥ㇱㇵㇶ𥄥𦒽𠣧𠊓𧢖𥞘𩔋цѰㄠſtʯʭɿʆʗʍʩɷɛ,əʏダヵㄐㄘR{gỚṖḺờṠṫảḙḭᴮᵏᴘᵀᵷᵕᴜᴏᵾq﮲ﲿﴽﭙ軌ﰬﶚﶧ﫲Ҝжюїкӈㇴffצּ﬘﭅﬈軌'ffistfflſtffतभफɳɰʊɲʎ𛁱𛁖𛁮𛀉 𛂯𛀞నఋŀŲ 𫟲𫠖𫞺ຆຆ ໹້໕໗ๆทԊꧢꧠ꧰ꓱ⿝⼑ŎḬẃẖỐẅ ,ờỰỈỗﮊDžȩꭏꭎꬻ꭮ꬿꭖꭥꭅ㇭神 ⾈ꓵꓑ⺄㄄ㄪㄙㄅㄇstA۵䞽ॶ𫞑𫝄㇉㇇゜軌𩜛𩳠Jﻺ‚Üမ႕ႌႊၐၸဓၞၞၡ៸wyvtᶎᶪᶹစဎ꣡꣰꣢꣤ٗ؋لㇳㇾㇻㇱ㆐㆔,,㆟Ⱶヤマފ޼ޝަݿݞݠݷݐ',ݘ,ݪݙݵ𬝉𬜁𫝨𫞘くせぉて¼óû×ó£…𛅑הㄙくԗԀ5606神45,神796'𪤻𫞧ꓐ㄁ㄘɥɺꓵꓲ3''7034׉ⱦⱠˆ“𫝋ȍ,ꩲ軌꩷ꩶꩧꩫఞ۔فڱێظペサ神ナᴦᵑ47 9238їﻂ䐊䔉㠸﬎ffiﬣ,לּᴷᴦᵛᵽ,ᴨᵤ ᵸᵥᴗᵈꚏꚉꚟ⻆rtǟƴ𬎎

Why https connections are so slow when debugging (stepping over) in Java?