Problem : I want to cast my object to its base class
Parent p = (Child) c; // this can be done
Child c = (Parent) p; // this can’t be done
Parent p = (Child) c; // this can be done
Child c = (Parent) p; // this can’t be done
/// Parent class
public class Parent
public class Parent
{
public string Name { get; set; }
}
/// Child class
public class Child : Parent
public class Child : Parent
{
public
string Extrainfo { get;
set; }
}
Well to convert between two classes you need to define implicit operator and it must be static
So the Child class will be
///Child class
///Child class
public class Child : Parent
{
public
static implicit
operator Parent(Child c)
{
return new Parent();
}
}
But the compiler will raise an error “user-defined conversions to or
from a base class are not allowed”
the compiler prevent the conversions to or form a base class L
the compiler prevent the conversions to or form a base class L
To solve this you need to add a new constructor to your derived class
(Child) and pass the parent into
this constructor and by using this Key word
you can copy your information from the base class to the derived class.
you can copy your information from the base class to the derived class.
so the new child object will have all the information from the base class and will also have the default values for the extra properties into the child class.
/// Child class
public class Child : Parent
public class Child : Parent
{
public string Extrainfo { get; set; }
public
Child()
{
}
public
Child(Parent p)
{
this.Name
= p.Name;
}
}
}
class Program
{
static
void Main(string[]
args)
{
Parent p = new Parent();
p.Name = "something";
Child c = new Child(p);
}
}