Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / August 2007

Tip: Looking for answers? Try searching our database.

How to cast class which implements an interface to a subclass

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
rjgeorge@zoominternet.net - 24 Aug 2007 18:33 GMT
I have a scenario where I have created a parent class, ParentTest,
which implements an interface, ITest.  The ParentTest class has a
method which returns an instance of the interface type.  Each child
class has a method which calls the parent's TestMethod method in order
to simplify method calls and make them more intuitive for each sub
type for developers.

In the ChildTest class, I want to return an instance of the ChildTest
in the GetData method.  However, I receive the following error:

An unhandled exception of type 'System.InvalidCastException' occurred
in test1.exe

Additional information: Unable to cast object of type
'TestNamespace.ParentTest' to type 'TestNamespace.ChildTest'.

Below is a simple example of what I am trying to accomplish.  Can
someone tell me if I am way off base with this approach?  If so, how
would I set this up correctly?

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace TestNamespace
{
   public enum TestEnum { A, B, C, D }

   public interface ITest
   {
       string Code {get;set;}
       string Description {get; set;}

       // Define simple method
       ITest TestMethod(TestEnum e, string s);
   }

   public class ParentTest : ITest
   {
       string _code;
       string _description;

       public ParentTest() : base() { }
       ParentTest(string e, string s)
           : base()
       {
           _code = e;
           _description = s;
       }

       public string Code {
           get
           {
               return _code;
           }
           set
           {
               _code = value;
           }
       }

       public string Description {
           get
           {
               return _description;
           }
           set
           {
               _description = value;
           }
       }

       public virtual ITest TestMethod(TestEnum e, string s)
       {
           // TODO: Create a method to do a look up by type and code
as passed by enum value and string
           Console.WriteLine("\n\nIn TestMethod.  e: " + e.ToString()
+ " s:" + s + "\n");
           ParentTest pt = new ParentTest(e.ToString(),
s);
           ITest i = pt as ITest;
           return i;
       }
   }

   public class ChildTest : ParentTest
   {
       public ChildTest() : base() { }

       public ChildTest GetData(string s)
       {
           ITest i = this.TestMethod(TestEnum.A, s);
           return (ChildTest)i;
       }

   }

   static class Program
   {
       [STAThread]
       static void Main()
       {
           ChildTest f = new ChildTest();
           ChildTest c = f.GetData("TestLookupCode");
           Console.WriteLine("\n\nCode: " + c.Code + " Description: "
+ c.Description + "\n\n\n");
       }
   }
}
Horacio Nuñez Hernández - 24 Aug 2007 18:52 GMT
>     public class ChildTest : ParentTest
>     {
[quoted text clipped - 7 lines]
>
>     }

just buble the return:

return this.TestMethod(TestEnum.A, s);

you can't cast from an interface to a type

regards
rjgeorge@zoominternet.net - 24 Aug 2007 19:01 GMT
On Aug 24, 1:52 pm, Horacio Nu?ez Hern?ndez <hnh12...@gmail.com>
wrote:
> >     public class ChildTest : ParentTest
> >     {
[quoted text clipped - 15 lines]
>
> regards

When I change to "return this.TestMethod(TestEnum.A, s);" as you
suggest, I get the following compile time error:

Error  1  Cannot implicitly convert type 'TestNamespace.ITest' to
'TestNamespace.ChildTest'. An explicit conversion exists (are you
missing a cast?)

Any suggestions?
Peter Duniho - 24 Aug 2007 19:07 GMT
> just buble the return:
>
>  return this.TestMethod(TestEnum.A, s);
>
> you can't cast from an interface to a type

If that were true, your suggestion wouldn't work either, since the
return value is ChildTest, but TestMethod returns an ITest.

Fortunately, it's not true you can't cast from an interface to a type.
The problem here is that the instance isn't a ChildTest instance.  It's
a ParentTest instance, and it's illegal to perform that cast.

Perhaps the OP meant to implement TestMethod in the ChildTest class as
well, and return a ChildTest instance from that method.  The fact that
TestMethod is virtual suggests that might be the case.  But without that
implemented override, the ParentTest.TestMethod is being called, and
that's returning a ParentTest instance, which of course cannot be cast
to a ChildTest instance.

Pete
Jon Skeet [C# MVP] - 24 Aug 2007 19:11 GMT
> >     public class ChildTest : ParentTest
> >     {
[quoted text clipped - 11 lines]
>
>  return this.TestMethod(TestEnum.A, s);

That won't work while the GetData method is declared to return
ChildTest.

> you can't cast from an interface to a type

Yes you can, but only if the runtime object is of the appropriate type.
The interface is a red herring here - the problem is that TestMethod is
returning an instance of ParentTest, not an instance of ChildTest.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Horacio Nuñez Hernández - 27 Aug 2007 13:25 GMT
> Horacio Nu?ez Hern?ndez <hnh12...@gmail.com> wrote:
>
[quoted text clipped - 26 lines]
> Jon Skeet - <sk...@pobox.com>http://www.pobox.com/~skeet  Blog:http://www.msmvps.com/jon.skeet
> If replying to the group, please do not mail me too

sorry about that
Jon Skeet [C# MVP] - 24 Aug 2007 19:09 GMT
<snip>

> Below is a simple example of what I am trying to accomplish.  Can
> someone tell me if I am way off base with this approach?  If so, how
> would I set this up correctly?

The problem is that TestMethod is returning an instance of ParentTest,
not ChildTest - that's why the cast is failing. It's not got anything
to do with the interface, really.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.