Software/C#.Net

Custom Type Conversions

charom 2011. 7. 7. 04:08
Explicit vs Implicit
 Explicit  Implicit
 Rectangle r = new Rectangle(10,4);
 Square s = (Square)r;
Square s1 = new Square();
Rectangle r2 = s1; 


explicit two different types conversion

 In Main method line 14 is impossible in general. Of course, if convert to Object type, it is possible. but in here, to do that, C# uses explicit operator ( see square class line 28). it is declared by static method. it gets one Rectangle type.
this is the way. By this technique, I can declare this method.
 
// This method requires a Square type. 
static void DrawSquare(Square sq) 
{ 
  Console.WriteLine(sq.ToString()); 
  sq.Draw(); 
} 
now I can call the DrawSquare() like below in a Main()

static void Main(string[] args) 
{ 
... 
  // Convert Rectangle to Square to invoke method. 
  Rectangle rect = new Rectangle(10, 5); 
  DrawSquare((Square)rect); --->1.it is called Square.explicit operator() 2.call DrawSquare()
  Console.ReadLine(); 
} 

Extending Square type conversion
Is this possible? How do I do?
// Converting an int to a Square. 
  Square sq2 = (Square)90; 
// Converting a Square to a int. 
  int side = (int)sq2;
need update Square class
public class Square 
{ 
... 
  public static explicit operator Square(int sideLength) <----declare
  { 
    Square newSq = new Square(); 
    newSq.Length = sideLength; 
    return newSq; 
  } 
 
  public static explicit operator int (Square s) <---check
  {return s.Length;} 
} 
How to convert <implicit way>?
public class Rectangle 
{ 
... 
  public static implicit operator Rectangle(Square s) 
  { 
    Rectangle r = new Rectangle(); 
    r.Height = s.Length; 
 
    // Assume the length of the new Rectangle with 
    // (Length x 2) 
    r.Width = s.Length * 2; 
    return r; 
  } 
}