Using the += Assignment Operator
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: Using the += Assignment Operator

  1. #1
    Join Date
    Jun 2012
    Posts
    11

    Using the += Assignment Operator

    According to Microsoft:

    Code:
    //string concatenation
    string s = "Hello";
    s += " world.";
    Console.WriteLine(s);
    //Output: "Hello world."
    In other words, x += y is the same as x = x + y.

    I would like to overload (or declare a new operator?) so that x += y is the same as x = y + x. I just want to reverse the order. So in MS's example, the output would be " world. Hello"

    Is this possible?

    Dan

  2. #2
    Join Date
    Feb 2012
    Location
    Strasbourg, France
    Posts
    116

    Re: Using the += Assignment Operator

    In C#.net you can override and define new operators overloads.

    Nice MSDN tutorial there :

    http://msdn.microsoft.com/en-us/libr...(v=vs.71).aspx

    So i would say to redefine it just do it for strings and should be something like that :
    Code:
    public static String operator +(String s1, String s2) 
       {
          return String.Contact(s2,s1)
       }
    Last edited by Erendar; June 22nd, 2012 at 08:54 AM.

  3. #3
    Join Date
    Jun 2012
    Posts
    11

    Re: Using the += Assignment Operator

    My preferred solution would be creating a "=+" operator, which would accurately mimic the desired behavior. The second-best would be overloading the += operator. Are either of those possible, and if so how would I go about that?

    Dan

  4. #4
    DataMiser is offline Super Moderator Power Poster
    Join Date
    Jul 2008
    Location
    WV
    Posts
    4,786

    Re: Using the += Assignment Operator

    I would say that if one were to redefine += to behave as suggested in the OP it would cause great confusion for anyone reading or writing the code as well as possibly confusing the compiler and causing many problems along the way.

    The opposite suggested in post #3 might not be so bad but would still confuse anyone reading the code.
    Always use [code][/code] tags when posting code.

  5. #5
    Join Date
    Jun 2012
    Posts
    11

    Re: Using the += Assignment Operator

    True. In retrospect I guess this is really just a post to say, "I wish this existed." I'll get over it and back to coding now.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center