Class Conversion (i.e. casting)

Last post 12-16-2004 11:59 PM by JOAC. 1 replies.

Sort Posts:

  • Class Conversion (i.e. casting)

    12-16-2004, 10:53 PM
    • Member
      50 point Member
    • lcarriere
    • Member since 03-14-2004, 4:14 PM
    • Posts 10
    does anyone know of a way that I can implement basically a custom queryinterface, for example:

    In some Class Library

    public interface ICollectionItem
    {
    ...
    }

    public class MyCollection: System.Collections.CollectionBase
    {
    ...
    public int Add(ICollectionItem Item)
    {
    return List.Add(Item);
    }
    }

    public interface IMyService
    {
    string ImplementedBy;
    }

    public class MyService: ICollectionItem, IMyService
    {
    ...
    public string ImplementedBy()
    {
    return "MyService";
    }
    }


    somewhere in the asp.net application code

    ...
    MyCollection myCollection = new MyCollection();
    MyCollection.Add(new MyService);
    ...

    //now this is what I would like to work...
    if (MyCollection is IMyService)
    {
    Label1.Text = (IMyService)MyCollection.ImplementedBy()
    }


    In Delphi (I am still a little new to C#), I used to do this by overriding the QueryInterface method in the MyCollection. I would override it so that would it would return the first item in the list that implements the Interface. Is there a way to do something like this in C#?
  • Re: Class Conversion (i.e. casting)

    12-16-2004, 11:59 PM
    • Participant
      1,880 point Participant
    • JOAC
    • Member since 06-18-2003, 3:59 PM
    • Posts 376
    You cannot use a collection like that. You must select an item from the collection and then do the cast. Use the as casting operator. It does not throw an exception like the (type) cast operator but instead will return null if the cast cannot be made.

    IMyService service = MyCollection[i] as IMyService;
    if (service != null)
    {
    Label1.Text = service.ImplementedBy;
    }
    Eric McVicker
Page 1 of 1 (2 items)