Hello,
Why we need implicit operator while creating child class in c sharp?
I am creating wrapper classes(c#) for the classes supported by one Automation tool.
ex. something like "public class MyClass : ToolClass" and so on for some other classes also
Concern:
1) Why do I need to add two implicit cast operators and a constructor to the newly created class(MyClass).
public static implicit operator MyClass(Element element);
public static implicit operator MyClass(string path);
2) As MyClass is child of ToolClass it should call this implicitly (as ToolClass is already doing this.)
Thanks in advance...
Loading
VulpesPosted Oct 26, 2013, 6:09 PM
Also the compiler knows that at least one of the operands of an operator overload must have the same type as the class in which it is defined because this is one of the restrictions of operator overloading in C#.
So if you have this:
MyClass mc = "c:\\somefile.txt";
the compiler infers that you're using MyClass's implicit operator to convert a string to a MyClass object.
Similarly, if you have this:
ToolClass tc = "c:\\someotherfile.txt";
the compiler infers that you're using ToolClass's implicit operator to convert a string to a ToolClass object.
Although this operator overload is inherited by MyClass, the compiler has no reason to think that you might be using it and, in fact, it is effectively inaccessible.
So, as static methods can't be virtual in .NET, you have no choice but to redefine the implicit operator in the child class as the parent class version can't be accessed and does something different (namely producing a ToolClass rather than a MyClass object) in any case.
sachin dimbrePosted Oct 26, 2013, 2:09 PM
If you're saying that there are similar operator overloads in the parent ToolClass then,
whilst they'll technically be inherited by MyClass, they won't be usable from there as they
will convert objects of the above types into ToolClass objects, not MyClass objects.
However as said in above paragraph as all other methods from parents are inherited by child why not these operator overloads from parent also, in that case we would not have to add these implicit operator in my child class.
Thanks in advance...
VulpesPosted Oct 25, 2013, 5:53 PM
If you're saying that there are similar operator overloads in the parent ToolClass then, whilst they'll technically be inherited by MyClass, they won't be usable from there as they will convert objects of the above types into ToolClass objects, not MyClass objects.