Cast is invalid on object

392 views Asked by At

I have this problem, when I try to cast the "batch" object, I am raised exception "Invalid cast". Can you help me out with why? The vault5 object exists and is correct.

public void batch(IEdmVault5 vault5)
{
    edmVault11 = (IEdmVault11)vault5;
    IEdmBatchRefVars batch = default(IEdmBatchRefVars);
    batch = (IEdmBatchRefVars)edmVault11.CreateUtility(EdmUtility.EdmUtil_BatchRefVars);

    //some code
}

Edit 1: Error message:

System.InvalidCastException HResult=0x80004002 Messaggio=Cast specificato non valido

2

There are 2 answers

2
Soumen Mukherjee On

I would suggest you try out this change , also

 public void batch(IEdmVault5 vault5)
{
    IEdmVault7 edmValult11 = null;
    if (vault5 == null)
    {
           vault5 = new EdmVault5();
    }
    edmVault11 = (IEdmVault11)vault5;
    IEdmBatchRefVars batch = default(IEdmBatchRefVars);
    batch = (IEdmBatchRefVars)edmVault11.CreateUtility(EdmUtility.EdmUtil_BatchRefVars);

    //some code
}

Besides given the nature of Solidworks API make sure that the installation and license are valid .

0
tcostin On

I ran into this today. The solution was to initialize COM for the current thread in STA mode.

  • For a WinForms app, this is already done for the main/UI thread (so that probably does not apply).
  • For a console app, consider adding [STAThread] to your Main() method.
  • If you're running this on background threads or tasks, you'll need to manipulate the thread state directly.