foreach and custom casting

Posted on 2005-04-13
Last Modified: 2012-06-27
I have 2 objects: A and B.

Object B contains object A, and is really a refined version of object A.  Ideally, object B would inherit from object A, but it must inherit from another object.

I have built a casting operator:
public static implicit operator A (B value) {      return value.A;}

I'm relatively new at C#, and I notice that this casting operator is not called on during the typical foreach statement.
That is, the following fails due to a cast exception:

foreach (A obj in ArrayListOfB) { }

My question is if there is an easy way around this.  Probably no, but I figured I'd send it out there.
Question by:gdbjohnson
    LVL 7

    Expert Comment

    You could just do this instead.

    for(int i = 0; i < ArrayListOfB.Length; i++)
        A aObj = (A)ArrayListOfB[i];
        //Now you have aObj.
    LVL 2

    Author Comment

    yes, I could do that, but this means I have to retouch all the code where I have used the foreach rule.  
    In that case, I would keep the foreach, but switch the cast to:

    foreach (B in ArrayListofB) {}
    and then use B.objA in the code.

    I recently had to rejig my object hierarchy paradigm because it didn't quite fit the application, but it's broken alot of code.  
    I guess the foreach construct has some kind of optimization that ignores my casting rule... not sure why (anyone know?), but it looks like my clever attempt at saving time will probably not work.

    I was just hoping by chance there was something that I would do/use to prevent having to retouch my code when object A and B are so closely related.
    LVL 3

    Accepted Solution


    public static explicit operator A (B value) {  return value.A; }

    This example worked for me...

    class EntryPoint
                static void Main(string[] args)
                      Family [] families = new Family [] { new Family(new Person("David","Jones")),new Family(new Person("Mike","Jones")),new Family(new Person("Neil","Jones")) } ;

                      foreach (Person father in families)

          public class Person
                public      Person(String firstName,String lastName)
                      _firstName = firstName;
                      _lastName = lastName;

                private String      _firstName;
                private String      _lastName;

                public      String      FirstName
                      get { return _firstName; }
                      set { _firstName = value; }
                public String      LastName
                      get { return _lastName; }

                public override string ToString()
                      return String.Format("{0}, {1}",_lastName, _firstName);

                public static explicit operator Person(Family family)
                      return family.Father;
          public class Family
                public Family(Person father)
                      _father = father;

                private Person      _father;

                public      Person      Father
                      get { return _father; }
    LVL 2

    Author Comment

    so it does work...  hmm.

    well, the implicit declaration contains the explicit one (at least, that's what I've read).  I just tried it, and it doesn't work, same as the implicit, which is what I expected.

    Although I didn't write it above, I've actually built a class that implements the IListSource, and IEnumerable interfaces, instead of using an arraylist, so I think the problem lies in my list implementation, combined with the fact that my hierarchy of objects is actually more complcated than what I wrote above.

    The list implementation casts to an object interface higher than where I have my operator defined (call it object C), which would be what is used to apply the cast to my object A.  Unfortunately, the operator isn't defined in C, it is defined in object B, so it doesn't work.  Yeah, this is why it doesn't work... not sure why I wold have thought that the added operator would act like an overridden method and carry down into parent objects... too bad for me, I guess.

    Thanks for helping me work that out. :)

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Live - One-on-One C# Help from Top Experts

    Solve your toughest problems, fast.
    C# experts are online now and ready to help you.

    This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
    Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    Hi everyone! This is Experts Exchange customer support.  This quick video will show you how to change your primary email address.  If you have any questions, then please Write a Comment below!

    761 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    8 Experts available now in Live!

    Get 1:1 Help Now