We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
close icon

exception Invalid Cast Exception : Specified cast is not valid

The below mentioend C# code snippnet will be executed while loading an usercontrol at its design time, but it throws an exception Invalid Cast Exception : Specified cast is not valid while executing this line Screen screen = Activator.CreateInstance(type,null ) as Screen ; however, the same code is executing properly when it is deployed as run time. can anybody help me out to resolve this problem ? string asmName = listBox3.SelectedItem.ToString (); Assembly asm = (Assembly) asmList[asmName]; listBox4.Items.Clear (); foreach(Type type in asm.GetTypes()) { if(type.IsClass && type.IsSubclassOf(typeof(Screen))) { Screen screen = Activator.CreateInstance(type,null ) as Screen ; // this line thrown an exception if(!classList.Contains (type.Name )) classList.Add (type.Name, screen); else classList[type.Name] = screen;

1 Reply

PC Pop Catalin June 8, 2005 03:09 PM UTC

just try using other overload of the CreateInstance Method try System.Activator.CreateInstance(System.Type type) >The below mentioend C# code snippnet will be executed while loading an usercontrol at its design time, but it throws an exception Invalid Cast Exception : Specified cast is not valid >while executing this line >Screen screen = Activator.CreateInstance(type,null ) as Screen ; > >however, the same code is executing properly when it is deployed as run time. > >can anybody help me out to resolve this problem ? > >string asmName = listBox3.SelectedItem.ToString (); >Assembly asm = (Assembly) asmList[asmName]; >listBox4.Items.Clear (); > >foreach(Type type in asm.GetTypes()) >{ >if(type.IsClass && type.IsSubclassOf(typeof(Screen))) > { >Screen screen = Activator.CreateInstance(type,null ) as Screen ; // this line thrown an exception > >if(!classList.Contains (type.Name )) > classList.Add (type.Name, screen); >else > classList[type.Name] = screen; >

Loader.
Live Chat Icon For mobile
Up arrow icon