explicit, implicit and operator
public class Name
{
/// <summary>
/// The implicit keyword is used to declare an implicit user-defined type conversion operator.
/// Use it to enable implicit conversions between a user-defined type and another type,
/// if the conversion is guaranteed not to result in a loss of data.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static implicit operator Name(string name)
{
return new Name(name);
}
/// <summary>
/// The explicit keyword declares a user-defined type conversion operator that must be
/// invoked with a cast
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static explicit operator string(Name name)
{
return name.Content;
}
/// <summary>
/// Use the operator keyword to overload a built-in operator or to provide a user-defined
/// conversion in a class or struct declaration.
/// </summary>
/// <param name="n1"></param>
/// <param name="n2"></param>
/// <returns></returns>
public static Name operator +(Name n1, Name n2)
{
return n1.Content + n1.Content;
}
string Content;
public Name(string name)
{
Content = name;
}
public override string ToString()
{
return Content;
}
}
class Program
{
public static void Main(string[] args)
{
Name n1 = new Name("Bruce");
Console.WriteLine(n1); // output: Bruce
Name n2 = "Bruce"; // auto cast
Console.WriteLine(n2); // output: Bruce
string n3 = (string)n1; // manual cast
Console.WriteLine(n3); // output: Bruce
Console.WriteLine(n1 + n2); // output: BruceBruce
}
}
reference:
explicit,
implicit,
operator