Conversion operators / cast operator overriding

  • Thread starter Thread starter Lieven De Foor
  • Start date Start date
Status
Not open for further replies.
L

Lieven De Foor

Guest
In C# you have the ability to override the implicit and explicit cast operator. From msdn: "C# enables programmers to declare conversions on classes or structs so that classes or structs can be converted to and/or from other classes or structs, or basic types. Conversions are defined like operators and are named for the type to which they convert. Either the type of the argument to be converted, or the type of the result of the conversion, but not both, must be the containing type." Say you have a class A, that has a member of type B. Class A can have an implicit/explicit operator B that allows to return B whenever a B is expected at compile time, BUT an A is passed in. E.g. class A { B BPart; static implicit operator B(A a) { return a.BPart; } } This could be particular usefull to implement simulated multiple inheritance (http://www.codeproject.com/Articles/10072/Simulated-Multiple-Inheritance-Pattern-for-C), but I'm sure other usefull use cases can be thought of. See also http://msdn.microsoft.com/en-us/library/09479473.aspx

Continue reading...
 
Status
Not open for further replies.
Back
Top