cast object to interface

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • mr.peteryu@gmail.com

    cast object to interface

    Hi,

    Can someone explain the idea behind casting to an interface?

    For example:
    -> I have an IInterface that contains a Read() method.
    -> I have an object "obj" that implements IInterface.

    Why would someone do the following and what does it mean?

    Object obj = new Object();
    IInterface var = (IInterface) obj
    var.Read()


    Thanks

  • Nicholas Paldino [.NET/C# MVP]

    #2
    Re: cast object to interface

    You can't do this. Object doesn't implement IInterface. The type that
    you create has to implement that interface (agree to the contract, in a
    sense), in order for the cast to succeed.

    You can't just cast any type to any other arbitrary type successfully.

    Hope this helps.


    --
    - Nicholas Paldino [.NET/C# MVP]
    - mvp@spam.guard. caspershouse.co m

    <mr.peteryu@gma il.com> wrote in message
    news:1133290678 .843875.207600@ f14g2000cwb.goo glegroups.com.. .[color=blue]
    > Hi,
    >
    > Can someone explain the idea behind casting to an interface?
    >
    > For example:
    > -> I have an IInterface that contains a Read() method.
    > -> I have an object "obj" that implements IInterface.
    >
    > Why would someone do the following and what does it mean?
    >
    > Object obj = new Object();
    > IInterface var = (IInterface) obj
    > var.Read()
    >
    >
    > Thanks
    >[/color]


    Comment

    • chris martin

      #3
      Re: cast object to interface

      > Hi,[color=blue]
      >
      > Can someone explain the idea behind casting to an interface?
      >
      > For example:
      > -> I have an IInterface that contains a Read() method.
      > -> I have an object "obj" that implements IInterface.
      > Why would someone do the following and what does it mean?
      >
      > Object obj = new Object();
      > IInterface var = (IInterface) obj
      > var.Read()
      > Thanks
      >[/color]

      Assuming that "Object obj = new Object();" really means "SomeObjectThat ImplemetsIInter face
      obj = new SomeObjectThatI mplemetsIInterf ace();", there really is no point,
      that I can think of, in casting to IInterface. If it is true that SomeObjectThatI mplemetsIInterf ace
      implements IInterface then you c(w)ould just call obj.Read();

      My guess is that the code was written by an inexperienced programmer. Please
      correct me if I'm wrong.

      Chris


      Comment

      • jeraldp@san.rr.com

        #4
        Re: cast object to interface

        Normally, if you have objects that support interface "IInterface ", your
        member variable will be defined as type "IInterface " also. However,
        you will most likely use reflection (either directly or via a class
        factory) to create your IInterface object, and reflection returns
        references to type object because it cannot pass back a specific type
        reference. At some point, that object reference must be cast to the
        interface. Reflection allows you to programmaticall y create types that
        you may not even know about at compile time.

        Comment

        • Jeff Louie

          #5
          Re: cast object to interface

          Base classes are useful for polymorphic behavior and as a transport
          mechanism.
          For polymorphic behavior one might create a collection of references of
          type
          IMyInterface. For transport one might pass a reference (variable) of
          type object.

          Regards,
          Jeff

          *** Sent via Developersdex http://www.developersdex.com ***

          Comment

          • Stefan

            #6
            Re: cast object to interface

            Hi,

            Check out my article, it might be helpful.



            Happy Coding,

            Stefan
            C# GURU


            "You always have to look beyond the horizon and can never be complacent
            -- God forbid we become complacent."

            Jozef Straus

            *** Sent via Developersdex http://www.developersdex.com ***

            Comment

            • methodios

              #7
              Re: cast object to interface

              Sorry if I was a little vague. Here's the code from the book:

              interface IStorable
              {
              void Read();
              void Write(object);
              int Status {get; set; }
              }


              public class Document : IStorable
              {
              public void Read() {...}
              public void Write (object obj) {...}

              public int Status {
              get { return status;}
              set { status = value; }
              }
              .....
              }

              -------

              Then here is my question:

              Document doc = new Document("Test Document");
              doc.status = -1;
              doc.Read();


              IStorable isDoc = (IStorable) doc;
              isDoc.Status = 0;
              isDoc.Read();

              Why would someone cast an object to an interface? Instead of
              isDoc.Status, can't we just use doc.Status ? This is all very confusing
              to me because I'm not quite sure what the purpose is for interfaces. I
              understand interfaces are contracts and contains no implementations .
              But why would someone want do the casting stated above? I'm kind of
              stuck right now in the book because I'm worried I might be missing a
              very important concept here which might be used later on; therefore I
              would like to get all this cleared up now.

              Thanks for all your help!
              -----------

              Comment

              • methodios

                #8
                Re: cast object to interface

                Hi Chris,

                That's what I was thinking. What is the need for var.Read() when you
                can just call obj.Read().

                Comment

                • Joanna Carter [TeamB]

                  #9
                  Re: cast object to interface

                  "methodios" <mr.peteryu@gma il.com> a écrit dans le message de news:
                  1133375744.9839 74.188690@g14g2 00...legr oups.com...

                  | Why would someone cast an object to an interface? Instead of
                  | isDoc.Status, can't we just use doc.Status ?

                  In the given example, yes you could do just that, but interfaces are
                  designed, amongst other things, to allow commoin behaviour across
                  hierarchies. IOW, you dont have to derive all your classes from one base
                  class to get a common behaviour. It also allows you to "derive from"
                  (implement) more than one interface.

                  So, you can not only have Document implement IStorable, but any other class
                  that you desire to have the Read, Write and Status behaviour. Thus I can
                  then have a list of IStorable items and treat them all the same, regardless
                  of what their real class is.

                  Also, I can implement the interface explicitly, thereby setting the
                  properties and methods to be essentially private to clients of the class.

                  public class Document : IStorable
                  {
                  void IStorable.Read( ) {...}
                  void IStorable.Write (object obj) {...}

                  public int IStorable.Statu s
                  {
                  get { return status;}
                  set { status = value; }
                  }
                  ...
                  }

                  Joanna

                  --
                  Joanna Carter [TeamB]
                  Consultant Software Engineer


                  Comment

                  • Joanna Carter [TeamB]

                    #10
                    Re: cast object to interface

                    "Joanna Carter [TeamB]" <joanna@not.for .spam> a écrit dans le message de
                    news: %23h4F9$d9FHA.3 720@TK2MSFTNGP1 0.phx.gbl...

                    Sorry, slight change required :

                    | public int IStorable.Statu s
                    | {
                    | get { return status;}
                    | set { status = value; }
                    | }

                    should be :

                    int IStorable.Statu s
                    {
                    get { return status;}
                    set { status = value; }
                    }

                    Joanna

                    --
                    Joanna Carter [TeamB]
                    Consultant Software Engineer


                    Comment

                    • tdavisjr

                      #11
                      Re: cast object to interface

                      Its looks like you are reading that C# book from O'Reilly as I have
                      that same example in my book. In your last sample code that you posted
                      I don't see the benefit of casting doc to ISorable interface.
                      Polymorphism is not acheived here. However, Its seems like the author
                      is just casting to IStorable as a test to see if doc implements the
                      IStorable interface. Again, the way shown is not a good way to do it.
                      I was use the "as" keyword.

                      Comment

                      • Joanna Carter [TeamB]

                        #12
                        Re: cast object to interface

                        "tdavisjr" <tdavisjr@gmail .com> a écrit dans le message de news:
                        1133377764.7359 50.108630@o13g2 00...legr oups.com...

                        | Its looks like you are reading that C# book from O'Reilly as I have
                        | that same example in my book. In your last sample code that you posted
                        | I don't see the benefit of casting doc to ISorable interface.
                        | Polymorphism is not acheived here. However, Its seems like the author
                        | is just casting to IStorable as a test to see if doc implements the
                        | IStorable interface. Again, the way shown is not a good way to do it.
                        | I was use the "as" keyword.

                        Then you would both end up with a runtime error if there were a problem with
                        the casting not being supported.

                        To be safe, you really need to do something like this :

                        {
                        IStorable isDoc = (IStorable) doc;
                        if (isDoc != null)
                        {
                        isDoc.Status = 0;
                        isDoc.Read();
                        }
                        }

                        Joanna

                        --
                        Joanna Carter [TeamB]
                        Consultant Software Engineer


                        Comment

                        • Bruce Wood

                          #13
                          Re: cast object to interface

                          The most important point to address here is that you're not quite sure
                          of the purpose of interfaces. Forget about the casting thing... it was
                          just a bad example in the book.

                          The value of interfaces doesn't come up immediately after you create
                          the object in question. After all, as you pointed out, you have the
                          object and you know what class it is, so why do you care about
                          interfaces at that point in the code? The answer is that you don't: you
                          have a reference to the object and that reference is declared as the
                          true type of the object, so you can get at all of the functionality of
                          the object. (For the pendantic types, yes, I know that that isn't
                          entirely true: there are circumstances in which you have to cast to an
                          interface in order to "see" methods and properties defined on that
                          interface, but this is an introduction, not a comprehensive guide. :-)

                          Interfaces come into their own when you start storing objects in
                          composite structures and/or passing them around. Think of it this way.

                          Let's say that you have a bit of functionality that you want to
                          implement in a bunch of objects that have no other logical realtionship
                          between them. IStorable isn't such a bad example. Let's say that you're
                          writing business software, so you have lots of classes defined like
                          Supplier, Customer, PurchaseOrder, Invoice, StockItem, and things like
                          that. All of these classes are stored in database tables somewhere. As
                          well, you have other classes that are just kind of housekeeping things
                          that you create, use, and destroy while your programs are running but
                          don't form part of your company's permanent data store.

                          OK, now what you want to do is write some sort of central software for
                          managing writes back to your database, caching, and refreshing the
                          cache from time to time. However, there's no common ancestor between
                          all of your "stored" classes: a StockItem and a Customer have nothing
                          to do with each other, other than the fact that they can be stored in
                          the database. Here, you have a few choices:

                          1. Make a common base class like StorableObject and inherit every
                          storable thing from it. That works great when you have only one
                          quality, "storable," and that's it. However, what happens when some of
                          these things, like PurchaseOrder and Invoice, should be "printable" ?
                          Well, you could give them a common ancestor, too, which works until you
                          end up with something that's "printable" and not "storable". Do you see
                          how, when you have only single inheritance to work with, embedding all
                          of this functionality in the class hierarchy starts to create fake base
                          classes with no purpose other than to offer some tidbit of
                          functionality, and how that in turn leads to a mess?

                          2. Teach your central data-managing classes about each "storable"
                          class. Most likely, each method in the data-managing classes would take
                          a type of "object" (so, no compile-time type checking here) and would
                          check the object at run time against all possible storable types of
                          things to see what it is, then cast it, then call its "Store" method.
                          So, every time you create a new storable class, you have to go an
                          modify all of the methods in your data-managing classes. Maintenance
                          nightmare.

                          3. Create an interface, and have all of those classes that otherwise
                          have nothing in common, implement IStorable. Now your data-managing
                          classes can deal only with objects that implement IStorable. *This* is
                          the big payoff. It's the ability to write code like this:

                          public class DataManager
                          {
                          WriteCollection ToDatabase(IEnu merable collection)
                          {
                          foreach (object o in collection)
                          {
                          IStorable storable = o as IStorable;
                          if (storable != null)
                          {
                          storable.Store( );
                          }
                          }
                          }
                          }

                          Notice that the method _doesn't care_ what kind of object is in the
                          collection, only that the object implements IStorable and so has a
                          Store() method. This is the big payoff: the ability to write generic
                          code that can deal with any object in your class hierarchy that
                          implements the specific behaviour it needs.

                          Here are some examples of interfaces I've created for my projects:

                          IKeyed: objects that implement IKeyed know their own primary keys. This
                          capability is implemented by many classes across my class hierarchy,
                          but whether an object knows its own primary key or not has nothing to
                          do with its place in the inheritance tree. Thus, the behaviour is
                          defined in an interface.

                          IHasListViewMod el: I have various controls that inherit from
                          Windows.Forms classes. As such, if I want a class that inherits from a
                          Panel and a class that inherits from a ListView to have some
                          functionality in common, I have no choice but to use an interface,
                          because the class hierarchy is already established by Microsoft. I
                          can't add functionality to Windows.Forms.C ontrol, for example, so I
                          have to "add in" functionality to selected of my custom controls using
                          an interface.

                          ISelfUpdatingCo llection: I have many different kinds of collections
                          that automatically keep themselves in synch with the database. Each one
                          of these inherits (logically) from the simple collection class of the
                          same type, so the self-updating collections can't have any common
                          ancestor that distinguishes them from collections that don't
                          self-update. To give you an idea of the class hierarchy, here are some
                          examples:

                          SelfKeyedCollec tion (base class)
                          StockItemCollec tion (derived from SelfKeyedCollec tion)
                          SelfUpdatingSto ckItemCollectio n (derived from
                          StockItemCollec tion)
                          SupplierCollect ion (derived from SelfKeyedCollec tion)
                          SelfUpdatingSup plierCollection (derived from
                          SupplierCollect ion)

                          etc. Now, if I want to tell the world that
                          SelfUpdatingSto ckItemCollectio n and SelfUpdatingSup plierCollection have
                          some functionality in common, and I want to write methods that can deal
                          with a SelfUpdating... Collection without caring what type it is, I have
                          to use an interface, because there's nowhere in the class hierarchy
                          that I can insert the appropriate common behaviour.

                          Comment

                          • Stefan

                            #14
                            Re: cast object to interface

                            Hi,

                            Check ou this article it will give a good example of how powerful the
                            use of polymorphism and the use of interfaces is:



                            Happy Coding,

                            Stefan

                            *** Sent via Developersdex http://www.developersdex.com ***

                            Comment

                            • methodios

                              #15
                              Re: cast object to interface

                              Thank you all for your help!

                              Comment

                              Working...