Popular Posts
Word break tag : <wbr/> (HTML5) The  HTML  <wbr>  tag  is  used  defines  a  potential  line  break  point  if  needed.  This  stands  for  Word  BReak. This  is  u... Enable SSL connection for Jsoup import org.jsoup.Connection; import org.jsoup.Jsoup; import javax.net.ssl.*; import java.io.IOException; import java.security.KeyManagement... File operation at SMB / UNC (network neighborhood) import java.io.IOException; import java.io.OutputStreamWriter; import jcifs.Config; import jcifs.smb.SmbFile; import jcifs.smb.SmbFileOutpu...
Stats
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