- implicit operator (from something to this) intake; can be cast
- explicit operator (from this to something) outtake; must be cast
lets say that we have a person class and a student class, but student does not inherit from person for whatever reason. now they obviously have things in common and you should be able to turn a Person into a student, and a student into a person.
using System;
namespace pc.ImplicitExplicitOperatorExample
{
public class Person
{
public string
FirstName { get; set; }
public string LastName
{ get; set; }
public Person(string
FirstName, string LastName)
{
this.FirstName = FirstName;
this.LastName = LastName;
}
public override string
ToString()
{
return FirstName + " " + LastName;
}
}
public class Student
{
public static int RunningID = 0;
public int ID { get; set; }
public string
FirstName { get; set; }
public string LastName
{ get; set; }
//Takes in a
person and converts it into a Student
public static implicit operator Student(Person p)
{
return new Student(p.FirstName, p.LastName);
}
//Takes in a
student and converts it into a Person
public static explicit operator Person(Student s)
{
return new Person(s.FirstName, s.LastName);
}
public Student(string
FirstName, string LastName)
{
ID = RunningID++;
this.FirstName = FirstName;
this.LastName = LastName;
}
public override string
ToString()
{
return ID + ") " + FirstName + " " + LastName;
}
}
public class Program
{
static void Main(string[] args)
{
//implicit
convert person to student
Student s1 = (Student)new Person("pavel", "Chooch");
Console.WriteLine(s1.ToString());
//explicitly
convert student to person
Person p1 = (Person)new Student("Ivan", "Pendaz");
Console.WriteLine(p1.ToString());
//implicit
convert person to student
Student s2 = new Person("Tomek", "Chooch");
Console.WriteLine(s2.ToString());
}
}
}
now we can see that we can convert a person to a student with no problems because it's implicit, but a student to a person requires an explicit cast. but if we changed our
//Takes in a student and converts it into a Person
public static explicit operator Person(Student s)
{
return new Person(s.FirstName, s.LastName);
}
//Takes in a student and converts it into a Person
public static implicit operator Person(Student s)
{
return new Person(s.FirstName, s.LastName);
}
Person p1 = new Student("Ivan", "Pendaz");
Console.WriteLine(p1.ToString());