IConvertible Casting 
Author Message
 IConvertible Casting

Hi

I have an interface called "Position"
I then have 2 classes that implement this interface. call them classA and
classB
public class classA:Position{...}
public class classB:Position{...}

when I try to cast from classA to classB I get an invalidCastException or
that I cant implicitly cast between these two types.
eg:
classA ca = new classA();
classB cb = new classB();

ca= (classA)cb; // this is the line that the logic breaks on

I know I can do this in Java . How do I do something like this in C#?
If anyone has some help for me it would be greatly appreciated.
--

Greg



Mon, 13 Dec 2004 17:46:45 GMT  
 IConvertible Casting
The way I see it is you need a base class. Here is a sample

using System;

namespace Polymorph
{
 public class classO
 {
  public classO(){}

  virtual public int Position()
  {
   return 0;
  }
 }

 public class classA:classO
 {
  public classA(){}

  override public int Position()
  {
   return 1;
  }
 }

 public class classB:classO
 {
  public classB(){}

  override public int Position()
  {
   return 2;
  }
 }

Quote:
}

Now all we need is a Test procedure like follow:

  private void bTest_Click(object sender, System.EventArgs e)
  {
   classA a = new classA();
   classB b = new classB();

   classO oO = new classO();
   classO oA = (classO) a;
   classO oB = (classO) b;

   Console.WriteLine(oO.Position());
   Console.WriteLine(oA.Position());
   Console.WriteLine(oB.Position());
  }

This should print 0,1,2 because classO is called followed by classA and
classB

Hope this helps
Francois

Quote:
> Hi

> I have an interface called "Position"
> I then have 2 classes that implement this interface. call them classA and
> classB
> public class classA:Position{...}
> public class classB:Position{...}

> when I try to cast from classA to classB I get an invalidCastException or
> that I cant implicitly cast between these two types.
> eg:
> classA ca = new classA();
> classB cb = new classB();

> ca= (classA)cb; // this is the line that the logic breaks on

> I know I can do this in Java . How do I do something like this in c#?
> If anyone has some help for me it would be greatly appreciated.
> --

> Greg



Mon, 13 Dec 2004 18:33:23 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. object must implement IConvertible

2. Do I really need to use IConvertible?

3. System.InvalidCastException: Object must implement IConvertible.

4. Help w/ IConvertible

5. Update Object must implement IConvertible??

6. old style casts vs new style casts

7. casting of struct element void pointer casting

8. Cast...always cast...

9. malloc: to cast or not to cast

10. to cast or not to cast?

11. Discarded Function Values (To Cast or Not to Cast)

12. When is a cast not a cast?

 

 
Powered by phpBB® Forum Software