Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding (cast)

Tags:

c#

casting

If I have a base class and two derived classes, and I want to implement the casting between the two derived classes by hand, is there any way to do that? (in C#)

abstract class AbsBase
{
   private int A;
   private int B;
   private int C;
   private int D;
}

class Imp_A : AbsBase
{
   private List<int> E;
}


class Imp_B : AbsBase
{
   private int lastE;
}

Generally I'll be casting from Imp_A -> Imp_B and I want the last value in the E list to be the 'LastE'. Also, what if there were three or more implementation classes (such as Salary, Hourly, Consultant, and Former Employees.)

Regardless of whether this is architecturally sound (I can't describe the whole application and be concise) is it possible?

I was going to write a converter, except that to my understanding a converter will create a new object of the Imp_B class, which I don't need because the 'employee' will only be one of the options at any one time.

-Devin

like image 828
DevinB Avatar asked Apr 07 '09 12:04

DevinB


People also ask

What is overriding in Java?

In Java, method overriding occurs when a subclass (child class) has the same method as the parent class. In other words, method overriding occurs when a subclass provides a particular implementation of a method declared by one of its parent classes.

What is type casting in Java?

Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size. byte -> short -> char -> int -> long -> float -> double.


2 Answers

You must implement a explicit or implicit operator.

class Imp_A : AbsBase
{
   public static explicit operator Imp_B(Imp_A a)
   {
      Imp_B b = new Imp_B();

      // Do things with b

      return b;
   }
}

Now you can do the following.

Imp_A a = new Imp_A();
Imp_B b = (Imp_B) a;
like image 152
Daniel Brückner Avatar answered Oct 29 '22 05:10

Daniel Brückner


I'd suggest you write Imp_B like this, if possible:

class Imp_B : Imp_A
{
    private int A;
    private int B;
    private int C;
    private int D;
    private int lastE { get { return this.E.Last(); } }
}

If you can't actually derive from ImpB, it's impossible for you to "treat" a ImpA object as an ImpB transparently the way you'd like, because they just aren't the same thing in memory. So, implement an explicit conversion.

like image 2
mqp Avatar answered Oct 29 '22 07:10

mqp