Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 572
  • Last Modified:

foreach and custom casting

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.
0
gdbjohnson
Asked:
gdbjohnson
  • 2
1 Solution
 
RealMrTeaCommented:
You could just do this instead.

for(int i = 0; i < ArrayListOfB.Length; i++)
{
    A aObj = (A)ArrayListOfB[i];
    //Now you have aObj.
}
0
 
gdbjohnsonAuthor Commented:
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.
0
 
wishguitarCommented:
Try

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

This example worked for me...

class EntryPoint
      {
            [STAThread]
            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)
                        Console.WriteLine(father.ToString());

                  Console.ReadLine();
            }
      }
      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; }
            }
      }
0
 
gdbjohnsonAuthor Commented:
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. :)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now