-
Notifications
You must be signed in to change notification settings - Fork 1
Conversion Methods
Mario Gutierrez edited this page Jan 7, 2017
·
1 revision
Explicit.
public static explicit operator Square(Rectangle r)
{
return new Square(r.Height);
}
You can now explicitly cast from Rectangle to Square.
Rectangle myRectangle = new Rectangle(4, 4);
Square mySquare = (Square)myRectangle;
Implicit.
public static implicit operator Rectangle(Square s)
{
return new Rectangle(s.Length, s.Length);
}
You can not implicitly cast from Square to Rectangle.
Square mySquare = new Square(4);
Rectangle myRectangle = mySquare;
In the implicit case, you also get the explicit cast for free. This makes sense because if it happens automatically, you should also be allowed to be verbose about it.
Rectangle myRectangle2 = (Rectangle)mySquare;
Conversion methods can be defined in structs as well.
- Abstract Classes
- Access Modifiers
- Anonymous Methods
- Anonymous Types
- Arrays
- Attributes
- Console I/O
- Constructors
- Const Fields
- Delegates
- Enums
- Exceptions
- Extension Methods
- File IO
- Generics
- Interfaces
- Iterators
- LINQ
- Main
- Null Operators
- Parameters
- Polymorphism
- Virtual Functions
- Reflection
- Serialization
- Strings
- Value Types
- "Base" Keyword
- "Is" and "As"
- "Sealed" Keyword
- nameof expression