473,804 Members | 2,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

InvalidCastExce ption

I have the following classes:

Public Class BaseClass
{
...
}

Public Class DerivedClass: BaseClass
{
...
}

The following code will throw out an InvalidCastExce ption:

BaseClass base = new BaseClass();
DerivedClass derived = (DerivedClass)b ase;

What do I need to do to make the casting successfully?


*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #1
4 1649
Here, you are trying to cast a generic type (base) to a specifc type (derived), which can't be done using a simple cast. Try using Type Convertors.
--
Rakesh Rajan
"Chris Li" wrote:
I have the following classes:

Public Class BaseClass
{
...
}

Public Class DerivedClass: BaseClass
{
...
}

The following code will throw out an InvalidCastExce ption:

BaseClass base = new BaseClass();
DerivedClass derived = (DerivedClass)b ase;

What do I need to do to make the casting successfully?


*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 16 '05 #2
Do you have that backward?

If you said
DerivedClass myderived = New DerivedClass();
BaseClass mybase = (BaseClass) myderived;

then I would understand you.

However, to do what you are trying to do does not make sense.

Say your derived class adds a method to the interface. Call it method "mm".

If you create a base object, and cast it to a derived type, then the
language should let you call the derived method "mm", right?

Now, let's say that the data needed by method "mm" was initialized in the
constructor of the derived class, WHICH YOU NEVER CALLED.

What should 'mm' do? If the language let's you do that, then I would not
use the language. My code could be forced into a situation that I could not
prepare for, except to totally abandon the concept of constructors, which is
wildly inefficient.

Thank goodness C# won't let you do this.

If you find a way, please tell me, so I can find a way to protect my code
from programmers who would use it!

--- Nick
"Chris Li" <ch********@yah oo.com> wrote in message
news:Of******** *****@TK2MSFTNG P11.phx.gbl...
I have the following classes:

Public Class BaseClass
{
..
}

Public Class DerivedClass: BaseClass
{
..
}

The following code will throw out an InvalidCastExce ption:

BaseClass base = new BaseClass();
DerivedClass derived = (DerivedClass)b ase;

What do I need to do to make the casting successfully?


*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 16 '05 #3

Nick, you are providing a good point and I have to admit that I did not
provide enough information about this situation. In my case, the base
class and the derived class have the same signiture (property and
method). The derived does not add any new property or method. You might
question why I want to generate a derived class. Here is the answer:

I have a base class and 2 derive classes. They have the same signiture
but one of the properties is of Arraylist type. Depending on the type of
derived class, this Arraylist contain a different class.

But I want the ability to cast the base class to derived class. Maybe
the TypeConvert class provide the answer for me.


*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #4
You want Generics, Chris. New feature of both C# 2.0 and Java 2.0... this
was already a feature of C++ that was overlooked in the release of C#.

Generics allow you to create classes that manage objects of a type where the
type is not known by the author of the generic class. The type is still
declared at design time, when the variable is declared, but one body of code
(one class) can be used to manage an arraylist where the arraylist manages a
list of elements of a type.

Google generics and c#

--- Nick

"Chris Li" <ch********@yah oo.com> wrote in message
news:%2******** ********@TK2MSF TNGP11.phx.gbl. ..

Nick, you are providing a good point and I have to admit that I did not
provide enough information about this situation. In my case, the base
class and the derived class have the same signiture (property and
method). The derived does not add any new property or method. You might
question why I want to generate a derived class. Here is the answer:

I have a base class and 2 derive classes. They have the same signiture
but one of the properties is of Arraylist type. Depending on the type of
derived class, this Arraylist contain a different class.

But I want the ability to cast the base class to derived class. Maybe
the TypeConvert class provide the answer for me.


*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 16 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1432
by: Johan Appelgren | last post by:
Hi, I'm trying to serialize a class hierarchy using System.Xml.Serialization.XmlSerializer from a class that is loaded as a Com object. But it fails with a InvalidCastException. I don't know what I'm doing wrong and it seems even the most simple cases fail. I tried with a simple class that looks like this public class Class1 {
1
3700
by: bob scola | last post by:
I have a csharp, VS 2003 solution for a winform application The application uses an object called a "matter" and the class is defined in matter.cs. I can load matter objects into a combobox Matter matters= v.Matters; comboBox1.Items.AddRange(matters);
11
3125
by: Roy Lawson | last post by:
I have no idea what is going on here. I wrote a simple application in VB.NET to generate a Crystal Report, and I am now trying to move it to ASP.NET with Crstal Enterprise. I wish I could tell you how the report works...but I can't even get past connecting to the database :-) I use the typical: Dim oConnection As New SqlConnection(strCon) Dim cmdText As String = "SELECT * FROM viewLogin WHERE " & _
4
2665
by: DOTNET | last post by:
Hi, Anybody help me regarding this error: I am assigning the values to the session variables when the button is clicked and passing these session variables to the next page and when I am printing these session variables they are printing. After that I am assigning these things in hidden object and in the form submit action I am receiving these hidden values like the following:
0
623
by: QA | last post by:
I am using a Business Scorecard Accelarator in a Sharepoint Portal 2003 using SQL Server 2005 I am getting the following error: Error,5/7/2005 10:50:14 AM,580,AUE1\Administrator,"Specified cast is not valid.","Microsoft.BusinessIntelligence.Scorecard.ScorecardException: Specified cast is not valid. ---> Microsoft.BusinessIntelligence.Scorecard.ScorecardException: Specified cast is not valid. ---> System.InvalidCastException: Specified...
1
18213
by: Marc | last post by:
Hi! I'm working with a C# client that calls a php web service. I've created a wrapper to call the service using .NET wsdl tool (adding a web reference). The call to the server works fine, it is serialized correctly, and the server returns a response (I've captured the response and it's correct!) but when the .NET deserialize this response, it throws the exception "System.InvalidOperationException: There is an error in XML
8
4274
by: Gamma | last post by:
I'm trying to inherit subclass from System.Diagnostics.Process, but whenever I cast a "Process" object to it's subclass, I encounter an exception "System.InvalidCastException" ("Specified cast is not valid"). How do I fix it ? using System.Diagnostics; .. .. class NewProcess: Process {
8
5781
by: =?Utf-8?B?YXVsZGg=?= | last post by:
i trying to collect windows services. i'm getting inconsistencies. the collection works every time locally. but remote collection yields different result depending on my lab environment. 1) in the same domain i start the collection on the remote machine i can get some 19 services without a problem then it will fail with: 'wmiService.ClassPath' threw an exception of type 'System.InvalidCastException'
4
1847
by: rsdev | last post by:
Hi, I have an InvalidCastException which is completely puzzling me. I have checked all the members in the stored procedure against my data provider and seems to be ok. Also in the stack trace it says ProcessRequestMain... +3742?? Here's the error; Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in...
8
4968
by: Joe HM | last post by:
Hello - I was wondering that the "cleanest" way is to determine whether a CType() will throw an InvalidCastException? I have data I receive as an Object and I want to convert it to a String whenever possible using CType(lObjectDummy, String) otherwise I will just ignore it. I could put a Try/Catch As System.InvalidCastException around it but I was wondering if that is the best solution. I once heard that exceptions should not be...
0
9571
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10318
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10069
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6845
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5505
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4277
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2976
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.