Windows Developer Center > Windows Forms Forums > Windows Forms General > Is ICloneable has something to do with the error: Unable to cast object of type 'X' to type 'Y'
Ask a questionAsk a question
 

AnswerIs ICloneable has something to do with the error: Unable to cast object of type 'X' to type 'Y'

  • Saturday, July 04, 2009 7:21 PMYovav Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    I'm not sure what are the benefits of implementing ICloneable,

    my web site is trapping a strange error and I wonder if that might have something to do with it,

     

    The error is: Unable to cast object of type 'X' to type 'Y'

    Where X is one object and Y is a different object (does not make sense)

    I'm convinced that this is not a casting error on my side since its working fine locally and I only get this error occasionally... don't know how to reproduce it...

    My objects are all using [Serializable]

    I think its happening in some cases when I'm loading objects back from cache or from the application state,

     

    Also, this service class is being accessed as an instance (using a singleton) like this:

    LanguageService.Instance.Get(resourceName, languageId, LanguageResourceType.String);

    (this is generating the error)

    And it is being called using another static class like this: 

    Resources.String("SomeString");

     

    I would like to hear any suggestions or if you think there is something wrong here.

    Thanks in advance.


    Respectfully - Yovav Gad

Answers

  • Saturday, July 11, 2009 10:37 PMYovav Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    OK, ICloneable has nothing to do with this error !

    I kept getting errors, so I implemented the deep copy and still got erros,


    Finally I found few articles that suggest it has something to do with static classes,
    The singleton pattern VS static classes (see more here)

    This is also a great find that convinced me to replace my static classes to singleton,
    as static class with a constructor could be more than ten times slower Static Constructor in C#

    I had some singleton classes together with some static classes, and they do not play nice together,
    so after I converted all to singleton classes the compiler is now able to follow the right execution order and my problem is solved.


    Thank you Kenneth Haugland for bringing up the "reference to the class" idea.


    Respectfully - Yovav Gad
    • Marked As Answer byYovav Saturday, July 11, 2009 10:37 PM
    •  

All Replies

  • Saturday, July 04, 2009 9:07 PMKenneth Haugland Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi

    If you use IClonable you are gananteed to get a full copy of what you are cloning... But you will also need to override the Clone() in you clss with impliments IClonable

    If you dont do that you could get references to you previous class values, but a new pointer to the values... If you get me....


    Kenneth
    • Marked As Answer byYovav Sunday, July 05, 2009 1:30 PM
    • Unmarked As Answer byYovav Saturday, July 11, 2009 10:38 PM
    •  
  • Saturday, July 04, 2009 9:24 PMYovav Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Thanks for the quick response :-)

    It really seems like I'm getting the previous pointers...


    Are you saying that the serialization process will execute .Clone() ?

    (if so - I don't understand why it does work most of the time)


    For this matter,

    should I use: public object Clone()

    or explicitly: object ICloneable.Clone()


    Also, some of my object properties are inherited from a base object, and I have other objects...
    is there a way to implement ICloneable so that the field names will not be hardcoded for each object separately ?
    (maybe run though some enumerator and create a clone objects with all available values ? - not sure how)

    Thanks in advance.

    Respectfully - Yovav Gad
  • Saturday, July 04, 2009 9:30 PMKenneth Haugland Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    No no.... can you instead paste the class you are coloing from?

    Should lokk something like this

    Class Something
    Implements ICloneable


    Public overrides Clone Implements ICloneable  (I think this is correct)

    Im wrigthing Vb ... but the results are the same.... If you dont implement the Over.. Clone like above you might the result of them beeing pointer insted of a new copy

    Dim d as new something

    add values to something...

    then

    Dim f as new something

    f = d.clone

    You should then get a copy if its done correcly, if you do it wrong you will get a pointer to the old values.....


    Not an expert, but I have implemented thin before... Hope my post helps you


    Kenneth
  • Saturday, July 04, 2009 9:41 PMYovav Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Has Code

    I guess that I c# this function does the override...

    public object Clone()
    {
        return (this.Clone());
    }
    

    I think I do need to set all the values before I return the object - right ?

    Respectfully - Yovav Gad
  • Saturday, July 04, 2009 9:48 PMYovav Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Has Code
    Or maybe I should use this:

    public object Clone()
    {
        return (this.MemberwiseClone());
    }
    

    I'm trying to figure out what does "shallow copy" means,
    found a nice article: You searched for 'icloneable without hardcoding'


    Respectfully - Yovav Gad
  • Saturday, July 04, 2009 9:49 PMKenneth Haugland Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    No I dont think that is correct....

    Public class point
    Implements ICloaneble

    Public Function Clone as Object Implements System.Iclonable.Clone
    Return New Point(xPos, Ypos)

    End function

    end class..


    this should be correct


    Kenneth
  • Saturday, July 04, 2009 9:52 PMKenneth Haugland Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Has Code
    Or maybe I should use this:

    public object Clone()
    
    {
    
        return (this.MemberwiseClone());
    
    }
    
    

    I'm trying to figure out what does "shallow copy" means,
    found a nice article: You searched for 'icloneable without hardcoding'


    Respectfully - Yovav Gad

    shallow copy means pointers to the same value on the heap

    deep copy means a copy value to a new location on the heap
    Kenneth
  • Saturday, July 04, 2009 9:59 PMYovav Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Has Code

    What do I need to use in order to avoid this random error that I'm getting (unable to cast...)

    Do you think that shallow copy can solve this problem ?


    Again, thanks for your help.
     

    By the way, in c# the syntax is like this: 

    public class Language : BaseObjectWithMaintenance, ICloneable
    


    Respectfully - Yovav Gad

    • Edited byYovav Saturday, July 04, 2009 10:01 PM
    • Edited byYovav Saturday, July 04, 2009 10:01 PM
    • Edited byYovav Saturday, July 04, 2009 10:02 PM
    • Edited byYovav Saturday, July 04, 2009 10:03 PM
    •  
  • Saturday, July 04, 2009 10:40 PMKenneth Haugland Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    hmm

    I dont think so... but that will depend on what the values are used for....

    If I wanted to meak sure that they actually got a deep copy I would do the following;

    Func Clone Implements ICloneable

    dim X2 as new X
    X2 = x

    return X2

    end function

    But your idea might work... my understanding of .NET is not at that level as you might reqiure.....
    Kenneth
  • Saturday, July 04, 2009 10:44 PMYovav Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Thanks,

    I will put it to the test and post here what worked.

    This problem is strange - only happends once in a while...
    Respectfully - Yovav Gad
  • Sunday, July 05, 2009 3:54 AMYovav Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Has Code
    I implemented ICloneable like this:

    public

     

    class Language : BaseObjectWithMaintenance, ICloneable

            #region ICloneable
    
            /// <summary>
            /// Clone this object using deep or shallow copy (deep copy is not implemented yet)
            /// <para>Deep copy will create a new object instance in memory</para>
            /// <para>Shallow copy will create a pointer to an existing onject</para>
            /// </summary>
            /// <param name="deepCopy"></param>
            /// <returns>object</returns>
            public object Clone(bool deepCopy)
            {
                if (deepCopy)
                {
                    // Implement deep copy with all members and return new instance of the object
                }
    
                return (this.MemberwiseClone());
            }
    
            /// <summary>
            /// Clone this object using shallow copy
            /// <para>Deep copy will create a new object instance in memory</para>
            /// <para>Shallow copy will create a pointer to an existing onject</para>
            /// </summary>
            /// <returns>object</returns>
            public object Clone()
            {
                return (Clone(false));
            }
    
            #endregion ICloneable
    

    No errors so far - lets wait few days, just to make sure it worked.
    Respectfully - Yovav Gad
  • Saturday, July 11, 2009 10:37 PMYovav Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    OK, ICloneable has nothing to do with this error !

    I kept getting errors, so I implemented the deep copy and still got erros,


    Finally I found few articles that suggest it has something to do with static classes,
    The singleton pattern VS static classes (see more here)

    This is also a great find that convinced me to replace my static classes to singleton,
    as static class with a constructor could be more than ten times slower Static Constructor in C#

    I had some singleton classes together with some static classes, and they do not play nice together,
    so after I converted all to singleton classes the compiler is now able to follow the right execution order and my problem is solved.


    Thank you Kenneth Haugland for bringing up the "reference to the class" idea.


    Respectfully - Yovav Gad
    • Marked As Answer byYovav Saturday, July 11, 2009 10:37 PM
    •  
  • Saturday, July 11, 2009 10:55 PMKenneth Haugland Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Yovav

    Glad to help... but I think you did most of the work... It always nice to learn something new though.... :)
    Kenneth