CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jun 2012
    Posts
    15

    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
    15

    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
    Join Date
    Jul 2008
    Location
    WV
    Posts
    5,362

    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
    15

    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
  •  





Click Here to Expand Forum to Full Width

Featured