Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. .NET (Core and Framework)
  4. Interfacecasting

Interfacecasting

Scheduled Pinned Locked Moved .NET (Core and Framework)
question
14 Posts 5 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • H Offline
    H Offline
    Hendrik Debedts
    wrote on last edited by
    #1

    What's the meaning of casting from a class to an interface?

    G 1 Reply Last reply
    0
    • H Hendrik Debedts

      What's the meaning of casting from a class to an interface?

      G Offline
      G Offline
      Guffa
      wrote on last edited by
      #2

      It means that you tell the compiler that instead of the reference to a specific class that you have, you want a reference to the same object but the type of the reference should be one of the interfaces that the class implements.

      --- b { font-weight: normal; }

      H 1 Reply Last reply
      0
      • G Guffa

        It means that you tell the compiler that instead of the reference to a specific class that you have, you want a reference to the same object but the type of the reference should be one of the interfaces that the class implements.

        --- b { font-weight: normal; }

        H Offline
        H Offline
        Hendrik Debedts
        wrote on last edited by
        #3

        I know, but what is the need of doing this? Why should someone do this?

        G 1 Reply Last reply
        0
        • H Hendrik Debedts

          I know, but what is the need of doing this? Why should someone do this?

          G Offline
          G Offline
          Guffa
          wrote on last edited by
          #4

          Hendrik Debedts wrote:

          I know

          So that's why you asked? ;)

          Hendrik Debedts wrote:

          but what is the need of doing this? Why should someone do this?

          To get a reference to an interface. If you for example use the Array.Sort method with an IComparer, you need a reference to an IComparer: Array.Sort(SomeArrayOfMine, MyOwnComparer); Here, the reference to the MyOwnComparer object is implicitly casted to IComparer.

          --- b { font-weight: normal; }

          H 1 Reply Last reply
          0
          • G Guffa

            Hendrik Debedts wrote:

            I know

            So that's why you asked? ;)

            Hendrik Debedts wrote:

            but what is the need of doing this? Why should someone do this?

            To get a reference to an interface. If you for example use the Array.Sort method with an IComparer, you need a reference to an IComparer: Array.Sort(SomeArrayOfMine, MyOwnComparer); Here, the reference to the MyOwnComparer object is implicitly casted to IComparer.

            --- b { font-weight: normal; }

            H Offline
            H Offline
            Hendrik Debedts
            wrote on last edited by
            #5

            Yes ok, but if you can cast an object to an interface, it means that the class of the object implements the interface and when the class implements the interface you don't have firstly cast the object to the interface

            P G 2 Replies Last reply
            0
            • H Hendrik Debedts

              Yes ok, but if you can cast an object to an interface, it means that the class of the object implements the interface and when the class implements the interface you don't have firstly cast the object to the interface

              P Offline
              P Offline
              PIEBALDconsult
              wrote on last edited by
              #6

              You wouldn't cast a class to an interface, it's unnecessary. But you may need to go the other way. If you have two classes (A and B) that implement an interface (I), you may have a method that takes a parameter of type I public void F ( I i ) then inside the method you may need to cast the parameter to it's actually type (however, this may be poor style) { if ( i is A ) { (A) i = blah blah blah } else if ( i is B ) { (B) i = blah blah blah } else throw something perhaps } but when calling F you needn't cast your instance to I A a = new A() ; F ( (I) a ) ; // legal, but needless F ( a ) ; // prefered

              S 1 Reply Last reply
              0
              • P PIEBALDconsult

                You wouldn't cast a class to an interface, it's unnecessary. But you may need to go the other way. If you have two classes (A and B) that implement an interface (I), you may have a method that takes a parameter of type I public void F ( I i ) then inside the method you may need to cast the parameter to it's actually type (however, this may be poor style) { if ( i is A ) { (A) i = blah blah blah } else if ( i is B ) { (B) i = blah blah blah } else throw something perhaps } but when calling F you needn't cast your instance to I A a = new A() ; F ( (I) a ) ; // legal, but needless F ( a ) ; // prefered

                S Offline
                S Offline
                Scott Dorman
                wrote on last edited by
                #7

                PIEBALDconsult wrote:

                You wouldn't cast a class to an interface, it's unnecessary

                This is sometimes necessary. If you have a class that implements two interfaces, each with a method of the same name you will need to explictly cast to the appropriate interface in order to access the correct method.

                public interface IList {
                public void Add(object x);
                }

                public interface IDictionary {
                public void Add(object x);
                }

                public class Test : IDictionary, IList {
                }

                Test t = new Test();
                ((IList)t).Add(x);
                ((IDictionary)t).Add(x);

                Without the explicit cast the compiler will not know which Add method you intended to call.

                ----------------------------- In just two days, tomorrow will be yesterday.

                P 1 Reply Last reply
                0
                • S Scott Dorman

                  PIEBALDconsult wrote:

                  You wouldn't cast a class to an interface, it's unnecessary

                  This is sometimes necessary. If you have a class that implements two interfaces, each with a method of the same name you will need to explictly cast to the appropriate interface in order to access the correct method.

                  public interface IList {
                  public void Add(object x);
                  }

                  public interface IDictionary {
                  public void Add(object x);
                  }

                  public class Test : IDictionary, IList {
                  }

                  Test t = new Test();
                  ((IList)t).Add(x);
                  ((IDictionary)t).Add(x);

                  Without the explicit cast the compiler will not know which Add method you intended to call.

                  ----------------------------- In just two days, tomorrow will be yesterday.

                  P Offline
                  P Offline
                  PIEBALDconsult
                  wrote on last edited by
                  #8

                  Ew. I sit corrected. I should have put in more qualifications like "usually unnecessary". But then you're probably getting into the reason C# only supports single inheritance.

                  S 1 Reply Last reply
                  0
                  • P PIEBALDconsult

                    Ew. I sit corrected. I should have put in more qualifications like "usually unnecessary". But then you're probably getting into the reason C# only supports single inheritance.

                    S Offline
                    S Offline
                    Scott Dorman
                    wrote on last edited by
                    #9

                    PIEBALDconsult wrote:

                    But then you're probably getting into the reason C# only supports single inheritance.

                    Yep. I was approaching this from a C# viewpoint, which does support single inheritance for the base class (you can inherit from as many interfaces as you want).

                    ----------------------------- In just two days, tomorrow will be yesterday.

                    1 Reply Last reply
                    0
                    • H Hendrik Debedts

                      Yes ok, but if you can cast an object to an interface, it means that the class of the object implements the interface and when the class implements the interface you don't have firstly cast the object to the interface

                      G Offline
                      G Offline
                      Guffa
                      wrote on last edited by
                      #10

                      Hendrik Debedts wrote:

                      when the class implements the interface you don't have firstly cast the object to the interface

                      Yes, sometimes you have to. You can't call a method using parameters of the wrong type. If a method expects an interface reference, you have to use an interface reference. You can't use the object reference, as it's not the correct type.

                      --- b { font-weight: normal; }

                      H 1 Reply Last reply
                      0
                      • G Guffa

                        Hendrik Debedts wrote:

                        when the class implements the interface you don't have firstly cast the object to the interface

                        Yes, sometimes you have to. You can't call a method using parameters of the wrong type. If a method expects an interface reference, you have to use an interface reference. You can't use the object reference, as it's not the correct type.

                        --- b { font-weight: normal; }

                        H Offline
                        H Offline
                        Hendrik Debedts
                        wrote on last edited by
                        #11

                        Oh yes you can, this code compiles without any problem ;) Here you pass an object of a class who implements the System.Collections.ICollection interface (Person) to a method that has a System.Collections.ICollection attribute (static void aMethod(System.Collections.ICollection i)) namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Person oPerson = new Person("Hendrik Debedts"); aMethod(oPerson); Console.ReadLine(); } static void aMethod(System.Collections.ICollection i) { Console.WriteLine(i); } } public class Person : System.Collections.ICollection { public string msNaam; public Person(string sNaam) { this.msNaam = sNaam; } public override string ToString() { return this.msNaam; } public void CopyTo(System.Array array, int index) { } public int Count { get { int anInteger = 0; return anInteger; } } public bool IsSynchronized { get { bool aBoolean = false; return aBoolean; } } public object SyncRoot { get { object anObject = new object(); return anObject; } } public System.Collections.IEnumerator GetEnumerator() { System.Collections.ArrayList arl = new System.Collections.ArrayList(); return arl.GetEnumerator(); } } }

                        G 1 Reply Last reply
                        0
                        • H Hendrik Debedts

                          Oh yes you can, this code compiles without any problem ;) Here you pass an object of a class who implements the System.Collections.ICollection interface (Person) to a method that has a System.Collections.ICollection attribute (static void aMethod(System.Collections.ICollection i)) namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Person oPerson = new Person("Hendrik Debedts"); aMethod(oPerson); Console.ReadLine(); } static void aMethod(System.Collections.ICollection i) { Console.WriteLine(i); } } public class Person : System.Collections.ICollection { public string msNaam; public Person(string sNaam) { this.msNaam = sNaam; } public override string ToString() { return this.msNaam; } public void CopyTo(System.Array array, int index) { } public int Count { get { int anInteger = 0; return anInteger; } } public bool IsSynchronized { get { bool aBoolean = false; return aBoolean; } } public object SyncRoot { get { object anObject = new object(); return anObject; } } public System.Collections.IEnumerator GetEnumerator() { System.Collections.ArrayList arl = new System.Collections.ArrayList(); return arl.GetEnumerator(); } } }

                          G Offline
                          G Offline
                          Guffa
                          wrote on last edited by
                          #12

                          Hendrik Debedts wrote:

                          Here you pass an object of a class who implements the System.Collections.ICollection interface (Person) to a method that has a System.Collections.ICollection attribute (static void aMethod(System.Collections.ICollection i))

                          ...Thereby causing an implicit cast of the reference. Exactly as in the code I showed earlier in the thread[^]. Just because you don't explicitly write the code for the casting, doesn't mean that the code you write doesn't do a cast.

                          --- b { font-weight: normal; }

                          P 1 Reply Last reply
                          0
                          • G Guffa

                            Hendrik Debedts wrote:

                            Here you pass an object of a class who implements the System.Collections.ICollection interface (Person) to a method that has a System.Collections.ICollection attribute (static void aMethod(System.Collections.ICollection i))

                            ...Thereby causing an implicit cast of the reference. Exactly as in the code I showed earlier in the thread[^]. Just because you don't explicitly write the code for the casting, doesn't mean that the code you write doesn't do a cast.

                            --- b { font-weight: normal; }

                            P Offline
                            P Offline
                            PIEBALDconsult
                            wrote on last edited by
                            #13

                            I would only use the term "cast" when it's explicit, not when it's implicit.

                            D 1 Reply Last reply
                            0
                            • P PIEBALDconsult

                              I would only use the term "cast" when it's explicit, not when it's implicit.

                              D Offline
                              D Offline
                              Dave Kreskowiak
                              wrote on last edited by
                              #14

                              Then what would you call it?

                              Dave Kreskowiak Microsoft MVP - Visual Basic

                              1 Reply Last reply
                              0
                              Reply
                              • Reply as topic
                              Log in to reply
                              • Oldest to Newest
                              • Newest to Oldest
                              • Most Votes


                              • Login

                              • Don't have an account? Register

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • World
                              • Users
                              • Groups