Results 1 to 12 of 12

Thread: Invalid Cast Exception when Working with Inherited Classes

  1. #1

    Thread Starter
    Frenzied Member Ideas Man's Avatar
    Join Date
    Aug 2002
    Location
    Australia
    Posts
    1,718

    Resolved Invalid Cast Exception when Working with Inherited Classes

    I know the title isn't exactly perfect, but the problem is hard to put it into words.

    Basically what I have is two classes, they are almost perfectly the same, however the derrived class contains some extra elements such as in this example.

    VB Code:
    1. 'Base Class
    2. Public Class CarBase
    3.  
    4.     Protected _Colour As String
    5.     Protected _Model As String
    6.     Protected _Make As String
    7.  
    8.     Public Property Colour() As String
    9.         Get
    10.             Return _Colour
    11.         End Get
    12.         Set(ByVal Value As String)
    13.             _Colour = Value
    14.             Call ValueChanged()
    15.         End Set
    16.     End Property
    17.     '
    18.     'Property Repeated for the Model and the Make
    19.  
    20.     Protected Overridable Sub ValueChanged()
    21.         'To be utilised in derrived classes
    22.     End Sub
    23.  
    24. End Class
    25.  
    26. 'Derrived Class
    27. Public Class Car
    28.     Inherits CarBase
    29.  
    30.     Private _ChangesMade As Boolean = False
    31.  
    32.     Protected Overrides Sub ValueChanged()
    33.         _ChangesMade = True
    34.     End Sub
    35.  
    36.     Public ReadOnly Property ChangesMade() As Boolean
    37.         Get
    38.             Return _ChangesMade
    39.         End Get
    40.     End Property
    41.  
    42. End Class

    Now, the problem is that i have other functions and stuff to manipulate the classes, they all work from the base class (CarBase) because that stores just the data items, nothing to manipulate them etc. The derrived class really only adds the ChangesMade and some other properties that don't really affect the stored data.
    I need both classes to be able to access the functions, but I don't really want to have to rewrite them to accomodate the two types of classes, some of which only return values so I can't overload them.

    When I try to assign a CarBase to a variable of type Car, I get an Invalid Cast Exception. Is there anyway I can allow it to do this type of action w/o raising an exception? The IDE doesn't detect an error and neither does the compiler, so there must not be anything wrong with the syntax.
    Last edited by Ideas Man; Jan 7th, 2005 at 08:22 AM.
    I use Microsoft Visual Basic 2005. (Therefore, most code samples I provide will be based around the .NET Framework v2.0, unless otherwise specified)

  2. #2
    Hyperactive Member
    Join Date
    Feb 2003
    Posts
    263

    Re: Invalid Cast Exception when Working with Inherited Classes

    Hi

    Why don't your manipulating function use the base class, why aren't you using your inherited class for all operations, you have the visibility set correctly so, Car.Colour should be fine in a Car Variable?

    I maybe being dumb, but sometimes when someone puts up a wrong response other will help

    Maybe you could post your other functions so that we can see what you actually trying to do. Tis a little confusing!

    Cheers

    Danny

  3. #3

    Thread Starter
    Frenzied Member Ideas Man's Avatar
    Join Date
    Aug 2002
    Location
    Australia
    Posts
    1,718

    Re: Invalid Cast Exception when Working with Inherited Classes

    I used the base class because it's generic and can be used throughout the program as common code, it is used more often than the more specific derrived code.

    I didn't quite understand what you ment by
    Why don't your manipulating function use the base class, why aren't you using your inherited class for all operations
    but I do use the base class as the object for the functions.

    After a bit more research, I found out that I can implicitly convert from a derrived class to the base class fine, but not the other way round which is annoying. The only way to go the other way is to specifically create a function that converts the base class into the derrived class.

    There's gotta be a better way of doing it than that. Any ideas anyone?

    Source=http://www.informit.com/articles/art...69107&seqNum=2
    I use Microsoft Visual Basic 2005. (Therefore, most code samples I provide will be based around the .NET Framework v2.0, unless otherwise specified)

  4. #4
    Hyperactive Member
    Join Date
    Feb 2003
    Posts
    263

    Re: Invalid Cast Exception when Working with Inherited Classes

    What i ment to type was:

    Why do your manipulating function use the base class, why aren't you using your inherited class for all operations?

    Sorry was typing fast as lunch was approaching!

    Danny

  5. #5

    Thread Starter
    Frenzied Member Ideas Man's Avatar
    Join Date
    Aug 2002
    Location
    Australia
    Posts
    1,718

    Re: Invalid Cast Exception when Working with Inherited Classes

    It uses the base class, because it is this that is common, the derrived class isn't common, so making the functions based around it wouldn't be logical would it?
    I use Microsoft Visual Basic 2005. (Therefore, most code samples I provide will be based around the .NET Framework v2.0, unless otherwise specified)

  6. #6
    Hyperactive Member
    Join Date
    Feb 2003
    Posts
    263

    Re: Invalid Cast Exception when Working with Inherited Classes

    Hi

    I am a little confused now, i thought you were using the car class and then wanting to access the CarBase class, in which case Car.(Some base class method) would be fine!

    Can you paste some code?

    Danny

  7. #7

    Thread Starter
    Frenzied Member Ideas Man's Avatar
    Join Date
    Aug 2002
    Location
    Australia
    Posts
    1,718

    Re: Invalid Cast Exception when Working with Inherited Classes

    Try copying the example in the first post and attempt todo this:
    VB Code:
    1. Dim CarB As New CarBase 'Creates a new instance of the Base Class
    2. Dim CarD As Car 'Creates an object of the derrived class
    3.  
    4. CarD = CarB 'Tries to assign the instance of the base class to the derrived class object

    If you do that, you should get an invalid cast exception, but if you reverse it, you will not get an exception and it will work fine.

    I want it to do the former because as I stated, the derrived class contains some other methods to modify the data, so I want to give the derrived class, all the data from the base class so it can use it and work on it, because all the functions associated with the classes, use the base class i.e. loading, saving etc. I need to use the base class because it is used as a common object, and all the other features of the derrived class aren't needed to be common to all aspects of the solution.
    I use Microsoft Visual Basic 2005. (Therefore, most code samples I provide will be based around the .NET Framework v2.0, unless otherwise specified)

  8. #8
    Hyperactive Member
    Join Date
    Feb 2003
    Posts
    263

    Re: Invalid Cast Exception when Working with Inherited Classes

    Hi

    Ok so here goes a stab in the dark not maybe the right way but here is how would understand it!

    Your Base Class really isn't a base Class, it is the overall Car Class, having the changes made flag in the SubClass really doesn't have any benefit to your code!!

    The example code you have given doesn't really warrant having a structure like you have, which maybe why your trying to do something that your not supposed to, (ie assiging a Base class to a derrived class).

    Maybe its not the code that is the problem its your structure. I am assuming you have more code in the two classes, if so could i see it, it may make it easier to understand.

    Will get to the bottom of this soon.

    Danny

  9. #9

    Thread Starter
    Frenzied Member Ideas Man's Avatar
    Join Date
    Aug 2002
    Location
    Australia
    Posts
    1,718

    Re: Invalid Cast Exception when Working with Inherited Classes

    Posting more of the code won't help, because it's just more of the same that's there, all I really need is to do what i said previously. It's beginning to look more and more like it can't be done (after reading that article). If you havn't read that yet, have a read and you'll see where i'm getting at.

    I gotta go, it's 2 in the morning here and i'm flat tired.
    I use Microsoft Visual Basic 2005. (Therefore, most code samples I provide will be based around the .NET Framework v2.0, unless otherwise specified)

  10. #10
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339

    Re: Invalid Cast Exception when Working with Inherited Classes

    You can't cast a base class to a derived class because it is not the derived class. Inheritance is only one way and always goes from less to more. Think about the term 'Inheritance' can you inherit something back to someone who is dead?

    The real issue here is that you should be creating an instance of the Car object then casting it to CarBase, send it through the functions and then convert it back to Car.
    VB Code:
    1. Dim c As New Car
    2. Dim bc As CarBase = c 'This may have to be cast to CarBase via the CType function
    3. Utilities.MyFunction(bc)
    4. Utilities.MyOtherFunction(bc)
    5. 'now back to c
    6. Msgbox(c.ChangesMade.ToString())
    Actually after thinking some more about this I bet the IDE will not even force you to convert Car to CarBase when passing to the function, but I could be wrong (maybe I didn't have OptionStrict on but I usually do).

  11. #11
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339

    Re: Invalid Cast Exception when Working with Inherited Classes

    Ok Curiosity got the better of me and I tested it and there is no need to down cast even with Option Strict on. So this will work:
    VB Code:
    1. Dim c As New Car
    2.         MsgBox(c.ChangesMade.ToString())
    3.  
    4.         Utilities.MyFunction(c)
    5.         Utilities.MyOtherFunction(c)
    6.         MsgBox(c.ChangesMade.ToString())

    Also just for reference this is the rest of the code I used to test:
    VB Code:
    1. 'Base Class
    2. Public Class CarBase
    3.  
    4.     Protected _Colour As String
    5.     Protected _Model As String
    6.     Protected _Make As String
    7.  
    8.     Public Property Colour() As String
    9.         Get
    10.             Return _Colour
    11.         End Get
    12.         Set(ByVal Value As String)
    13.             _Colour = Value
    14.             Call ValueChanged()
    15.         End Set
    16.     End Property
    17.     '
    18.     'Property Repeated for the Model and the Make
    19.  
    20.     Protected Overridable Sub ValueChanged()
    21.         'To be utilised in derrived classes
    22.     End Sub
    23.  
    24. End Class
    25.  
    26. 'Derrived Class
    27. Public Class Car
    28.     Inherits CarBase
    29.  
    30.     Private _ChangesMade As Boolean = False
    31.  
    32.     Protected Overrides Sub ValueChanged()
    33.         _ChangesMade = True
    34.     End Sub
    35.  
    36.     Public ReadOnly Property ChangesMade() As Boolean
    37.         Get
    38.             Return _ChangesMade
    39.         End Get
    40.     End Property
    41.  
    42. End Class
    43.  
    44. Public Class Utilities
    45.  
    46.     Public Shared Sub MyFunction(ByVal base As CarBase)
    47.         base.Colour = "Red"
    48.     End Sub
    49.  
    50.     Public Shared Function MyOtherFunction(ByVal base As CarBase) As String
    51.         base.Colour &= "2"
    52.         Return base.Colour
    53.     End Function
    54.  
    55. End Class

  12. #12

    Thread Starter
    Frenzied Member Ideas Man's Avatar
    Join Date
    Aug 2002
    Location
    Australia
    Posts
    1,718

    Re: Invalid Cast Exception when Working with Inherited Classes

    Thanks Edneeis for you reply. I guess I have to understand now that there is no way to go up the tree, only down. I was also aware of the down casting which you pointed out (I think i mentioned that).

    Anyway, I solved it by making a converter function in the derrived class, maybe not the best solution but cause all it has todo is transfer the properties values from one object to another, it was easy todo.

    VB Code:
    1. 'Example
    2. Public Class Car
    3.  
    4. '... All the other stuff
    5.  
    6. Public Shared Function Convert(SourceObject as CarBase) As Car
    7.     Dim NewCar As New Car
    8.  
    9.     With NewCar
    10.         .Colour = SourceObject.Colour
    11.         'Etc with the other properties
    12.     EndWith
    13.  
    14.     Return NewCar
    15. End Sub
    I use Microsoft Visual Basic 2005. (Therefore, most code samples I provide will be based around the .NET Framework v2.0, unless otherwise specified)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width