I actually missed this in a job interview…but ended up getting the job! C# does not provide a copy constructor but does provide a way to do such operations using the explicit keyword as a way to do it. What happens is that in a cast situation, one casts from one object type to a different object type. Here is an example where one could go from a dataset to another object such as this:

Dataset DS = GetDataSet();
myclass abc = (myclass) DS;

The cast actually returns a new myclass object. That magic is done using the explicit keyword. One can do many such casts as needed for differing objects Here is an example, call the static Usage() on the class, where I explicitly cast one class object to another. A new object is returned and it prints out the value from the cast’ed object:

// Class which will be cast-ed from
public class OtherClass
{

   public OtherClass() { originalValue = 42; }

   public int originalValue;
}

// Class We are interested in.
public class ExplicitTestClass
{
     private int _myValue;

     // Do nothing Constructor
     public ExplicitTestClass() { }

     // Mimic Conversion Constructor
     public static explicit operator ExplicitTestClass(OtherClass oc)
     {
         ExplicitTestClass etc = new ExplicitTestClass();

         etc._myValue = oc.originalValue;

         return etc;

     }

     public override string ToString()
     {
         return _myValue.ToString();
     }

     // This is just to show it working
     // as is not needed outside of this
     // blog and could/should be found outside the class.
     public static void Usage()
     {
         OtherClass oc = new OtherClass();

         ExplicitTestClass myETC = (ExplicitTestClass)oc;

         Console.WriteLine(myETC.ToString()); // Prints 42

     }
 }
  • Line 02: This class will hold the value which we are interested in. It is the target class which will be cast-ed from.
  • Line 11: This is our result class which after the cast will be our result.
  • Line 16: This constructor will create the blank slate for our operations.
  • Line 19: This allows the cast to our target class OtherClass, which we will get its value to and return a new valid ExplicitTestClass object.
  • Line 21: This new’s the new object to eventually be returned.
  • Line 23: This is the copy constructor esque section. We are only interested in one value…but there could be others.
  • Line 25: Return the valid new object.
  • Line 29: Just show the value we are looking for…
  • Line 37: This is only for this blog post and shows how to use the cast in a real world situation.
Share

Tags: , ,