2

I have the following code:

namespace ConsoleApplication2
{
    public class Test1
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public Test1(string name,string lastName,int age)
        {
            FirstName = name;
            LastName = lastName;
            Age = age;
        }
        //Error:  user-defined conversions to or from a derived class are not allowed 
        public static implicit operator Test2(Test1 d)
        {
            return new Test2(d.FirstName,"MiddleName" , d.LastName, d.Age);
        }
    }
    public class Test2 : Test1
    {
        public string MiddleName { get; set; }

        public Test2(string name,string middleName, string lastName, int age) : base(name, lastName, age)
        {
             MiddleName = middleName;
        }
    }
}

I get error about conversion to derived class. But I don't understand why is the conversion to a derived class not allowed ??

Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46
  • http://stackoverflow.com/questions/3401084/user-defined-conversion-operator-from-base-class – Dmitry Bychenko Apr 10 '17 at 12:30
  • @DmitryBychenko No flag, looks like a dupe to me? I'd support the hammer if you wanna use it. – DavidG Apr 10 '17 at 12:31
  • @DmitryBychenko no there is anwser for why I can't write implicit operator in the derived class , but not in the Base – Samvel Petrosov Apr 10 '17 at 12:33
  • 1
    @S.Petrosov It's the same reason, there'd still be multiple conversion paths, i.e. madness. – DavidG Apr 10 '17 at 12:33
  • @DavidG no, I can't write Test1 t1 = new Test1("AAA","BBB",21); Test2 t2 = (Test2)t1; because I will get RunTime Error for not being able to cast from Test1 to Test2 while implicit operator would resolve this if it was possible – Samvel Petrosov Apr 10 '17 at 12:37
  • @DavidG Moreover, the question was about explicit operators while mine is about implicit – Samvel Petrosov Apr 10 '17 at 12:39
  • 2
    And yet, it's *still the same reason*. – DavidG Apr 10 '17 at 12:40
  • 2
    @S.Petrosov - the problem is in your *second* line - `Test2 t2 = (Test2)t1;` . The compiler doesn't know that `t1` *isn't* already a `Test2`, when its compiling that line and so that built in cast has got to *be* a candidate. – Damien_The_Unbeliever Apr 10 '17 at 12:43

0 Answers0