Search code examples
c#operator-overloading

operator overloading for string concatenation c#.net


I have my custom data type as

public class AppIdentiy
{
    public string ID { get; set; }

    public static implicit operator AppIdentiy(string userID)
    {
        var result = new AppIdentiy()
        {
            ID = userID
        };
        return result;
    }

    public static implicit operator string(AppIdentiy identity)
    {
        if (identity is null)
            return string.Empty;
        else if (string.IsNullOrEmpty(identity.ID))
            return string.Empty;

        return identity.ID;
    }

    //public static string operator +(AppIdentiy a) => a.ID;

}

I am using this AppIdentiy like this for example

AppIdentiy myIdentity  = "[email protected]";

string email = myIdentity; //setting the variable email with the value '[email protected]'

string comment  = "this is user email address '" + myIdentity + "' generated by xyz app"; //this is not working, I am expecting here when I use '+' operator with my datatype its value should populate here like 

"this is user email address '[email protected]' generated by xyz app"

I am not getting how to decorate the + operator overloading in my AppIdentiy class


Solution

  • The + operator takes two operands - the left and right values (at least one of which must be of the declaring type); hence you could have any-or-all-of:

    public static string operator +(AppIdentiy x, string y) => ...;
    public static string operator +(string x, AppIdentiy y) => ...;
    public static string operator +(AppIdentiy x, AppIdentiy y) => ...;
    

    However, it seems unlikely that this is actually what you want to do here! You shouldn't usually need to override how string addition works, and it already works as I would expect for your type.