Note that there are some explanatory texts on larger screens.

plurals
  1. POAre implicity/explicit conversion methods inherited in C#?
    primarykey
    data
    text
    <p>I'm not sure what I'm doing wrong here. I have a generic class, which is basically a glorified integer, with a few methods for certain string formatting, as well as into/from string and int conversions:</p> <pre><code>public class Base { protected int m_value; ... // From int public static implicit operator Base(int Value) { return new Base(Value); } ... // To string public static explicit operator string(Base Value) { return String.Format("${0:X6}", (int)Value); } } </code></pre> <p>And it functions fine. I can successfully use implicit and explicit conversions:</p> <pre><code>Base b = 1; Console.WriteLine((string)b); // Outputs "$000001", as expected. </code></pre> <p>Then I derive from this class, different child classes, which turn on/off different named bits in m_value. For example:</p> <pre><code>public class Derived : Base { } </code></pre> <p>And then I cannot use my implicit to/from int conversions:</p> <pre><code>Derived d = 3; // Cannot implicitly convert type 'int' to 'Derived'. An explicit conversion exists (are you missing a cast?) </code></pre> <p>Even this gives the same error:</p> <pre><code>Derived d = (int)3; </code></pre> <p>Are the implicit/explicit conversions not inherited in the derived class? This will require a lot of code copying if not.</p> <p><strong>RESPONSE</strong> Thank you so much for the quick responses! You all deserve the 'answer' checkmark, they're all very good answers. The key is to think about the types on both sides of the equal sign. Now that I think about it like that, it makes perfect sense.</p> <p>I obviously only have to re-write my "to Derived" conversions. The "to Int32, String, etc" conversions still apply.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload