Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Operator overloading with strings

Operator overloading with strings

Scheduled Pinned Locked Moved C#
helpquestion
14 Posts 8 Posters 3 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • H hzs

    I need to apply arithmatic operations on string i.e. string1 = "12"; string2 = "10"; string3 = string1+ string2; and now I want string3 to contain "22" currently I'm using functions like Add(string1, string2) which is a pain. The problem is that the above statement (string3 = string1+ string2) will concatenate the two strings not add them and overloading the + operator doesn't work. The compiler gives an error saying One of the parameters of a binary operator must be a containing type. If I make my own String class, the overloading works fine. Anyone got any ideas? thanks in advance...hasan

    J Offline
    J Offline
    J Dunlap
    wrote on last edited by
    #2

    You have to convert them to a numeric type first.

    string3=(Int32.Parse(string1)+Int32.Parse(string2)).ToString();

    "Blessed are the peacemakers, for they shall be called sons of God." - Jesus
    "You must be the change you wish to see in the world." - Mahatma Gandhi

    H 1 Reply Last reply
    0
    • J J Dunlap

      You have to convert them to a numeric type first.

      string3=(Int32.Parse(string1)+Int32.Parse(string2)).ToString();

      "Blessed are the peacemakers, for they shall be called sons of God." - Jesus
      "You must be the change you wish to see in the world." - Mahatma Gandhi

      H Offline
      H Offline
      hzs
      wrote on last edited by
      #3

      right. But I don't want to have to convert the stings to ints every time as i'm using around 15 for each calculation and doing what you suggested would make the code sort of confusing. I think it can be done using operator overloading so that the developer can add two strings simply by writing string3=string1+string2 Anyone with some other solution?

      I J H R 4 Replies Last reply
      0
      • H hzs

        right. But I don't want to have to convert the stings to ints every time as i'm using around 15 for each calculation and doing what you suggested would make the code sort of confusing. I think it can be done using operator overloading so that the developer can add two strings simply by writing string3=string1+string2 Anyone with some other solution?

        I Offline
        I Offline
        Ista
        wrote on last edited by
        #4

        public static string operator + ( string s1, string s2 ) { return (Int32.Parse(s1) + Int32.Parse(s2)).ToString(); } I'm not an expert yet, but I play one at work. Yeah and here too.

        H 1 Reply Last reply
        0
        • H hzs

          right. But I don't want to have to convert the stings to ints every time as i'm using around 15 for each calculation and doing what you suggested would make the code sort of confusing. I think it can be done using operator overloading so that the developer can add two strings simply by writing string3=string1+string2 Anyone with some other solution?

          J Offline
          J Offline
          Julian Bucknall MSFT
          wrote on last edited by
          #5

          Just want to point something out: Can you imagine the maintainance nightmare that would result from doing what you propose? If you read string3 = string1 + string2; in your code 6 or 12 months from now, would you know whether it meant "concatenate" or "treat the strings as numbers and add"? Would your replacement? What I'm saying is that although the language might allow you to do what you want, do you really want to do it? It's great writing software that's only used once, to prove a point, as it were, but the reality of our game is that we generally have to write code that we'll have to maintain down the road (and if not us, then someone else). In that case, the simpler you express the intent of your program in code, the simpler it is to test and maintain, and the easier it is to go home at 5 o'clock. My recommendation is to create a small class that encapsulates what you want to do. Override the + operator (and the += operator, and the - operator and the -= operator) to your heart's content at that point. It won't be as confusing as "sometimes in my code the + operator on strings means this, other times it means that". Cheers, Julian Program Manager, C# This posting is provided "AS IS" with no warranties, and confers no rights.

          H 1 Reply Last reply
          0
          • H hzs

            right. But I don't want to have to convert the stings to ints every time as i'm using around 15 for each calculation and doing what you suggested would make the code sort of confusing. I think it can be done using operator overloading so that the developer can add two strings simply by writing string3=string1+string2 Anyone with some other solution?

            H Offline
            H Offline
            Heath Stewart
            wrote on last edited by
            #6

            The fact of the matter is, that unless you write your own CLR, you'll have to convert to numbers (Int32, Int64, whatever) even if you create your own class and overload the + operator - there is no way around it. All you'll be doing then, however, is making it look like you're not - it's still happening under the covers. Using the Add(string, string) method you mentioned earlier is the best way - always modularize your code. This will allow you to use a simple, short statement to add the numeric values of the strings and will allow you to optimize the algorithm once in the future as opposed to finding all lines where you do this and change them. I recommend using a static method too, so you don't have to worry about instantiating some class just to add a couple of strings values.

            -----BEGIN GEEK CODE BLOCK----- Version: 3.21 GCS/G/MU d- s: a- C++++ UL@ P++(+++) L+(--) E--- W+++ N++ o+ K? w++++ O- M(+) V? PS-- PE Y++ PGP++ t++@ 5 X+++ R+@ tv+ b(-)>b++ DI++++ D+ G e++>+++ h---* r+++ y+++ -----END GEEK CODE BLOCK-----

            1 Reply Last reply
            0
            • H hzs

              right. But I don't want to have to convert the stings to ints every time as i'm using around 15 for each calculation and doing what you suggested would make the code sort of confusing. I think it can be done using operator overloading so that the developer can add two strings simply by writing string3=string1+string2 Anyone with some other solution?

              R Offline
              R Offline
              Rein Hillmann
              wrote on last edited by
              #7

              I'm curious. Assuming you could overload this operator, what would you do with the following code: string1 = "12"; string2 = "10"; string3 = "abc"; string3 = string1 + string2 + string3; Would you want this to be "22abc" or "1210abc"? There's a good reason not to do this - it's confusing for developers maintaining your code. Personally, I think you should either create a new class and overload or you should just continue using the Add() method.

              H 1 Reply Last reply
              0
              • I Ista

                public static string operator + ( string s1, string s2 ) { return (Int32.Parse(s1) + Int32.Parse(s2)).ToString(); } I'm not an expert yet, but I play one at work. Yeah and here too.

                H Offline
                H Offline
                hzs
                wrote on last edited by
                #8

                Your solution Ista wrote: public static string operator + ( string s1, string s2 ) { return (Int32.Parse(s1) + Int32.Parse(s2)).ToString(); } doesn't work...I've had already tried it. The compiler generates an error: One of the parameters of a binary operator must be a containing type". So the + operator can't be overloaded in this way.

                I 1 Reply Last reply
                0
                • J Julian Bucknall MSFT

                  Just want to point something out: Can you imagine the maintainance nightmare that would result from doing what you propose? If you read string3 = string1 + string2; in your code 6 or 12 months from now, would you know whether it meant "concatenate" or "treat the strings as numbers and add"? Would your replacement? What I'm saying is that although the language might allow you to do what you want, do you really want to do it? It's great writing software that's only used once, to prove a point, as it were, but the reality of our game is that we generally have to write code that we'll have to maintain down the road (and if not us, then someone else). In that case, the simpler you express the intent of your program in code, the simpler it is to test and maintain, and the easier it is to go home at 5 o'clock. My recommendation is to create a small class that encapsulates what you want to do. Override the + operator (and the += operator, and the - operator and the -= operator) to your heart's content at that point. It won't be as confusing as "sometimes in my code the + operator on strings means this, other times it means that". Cheers, Julian Program Manager, C# This posting is provided "AS IS" with no warranties, and confers no rights.

                  H Offline
                  H Offline
                  hzs
                  wrote on last edited by
                  #9

                  Hmm...I believe you're right about the maintinence...overloading would cause a lot of confusion so I guess I'll just use my Add & Sub functions. However you've mentioned that "although the language might allow you to do what you want, do you really want to do it?" and I'm curious how does the languge allow me to do what I want i.e how does it allow me to overload +, - operators etc. for primitive datatypes like int and sting. Hasan P.S. The part about going home at 5 went straight to my heart :-D

                  I 1 Reply Last reply
                  0
                  • R Rein Hillmann

                    I'm curious. Assuming you could overload this operator, what would you do with the following code: string1 = "12"; string2 = "10"; string3 = "abc"; string3 = string1 + string2 + string3; Would you want this to be "22abc" or "1210abc"? There's a good reason not to do this - it's confusing for developers maintaining your code. Personally, I think you should either create a new class and overload or you should just continue using the Add() method.

                    H Offline
                    H Offline
                    hzs
                    wrote on last edited by
                    #10

                    I've decided to continue using my Add() method. However your point about the "abc" string; since I would be converting the string to an int in my overloaded method, I'd get an error in case "abc" were used; so to avoid this I'd check that the user only enters numeric data. that out of the way, I'd still like to know how to overload + for string or int. (just curios). thanks....hasan

                    F I 2 Replies Last reply
                    0
                    • H hzs

                      I've decided to continue using my Add() method. However your point about the "abc" string; since I would be converting the string to an int in my overloaded method, I'd get an error in case "abc" were used; so to avoid this I'd check that the user only enters numeric data. that out of the way, I'd still like to know how to overload + for string or int. (just curios). thanks....hasan

                      F Offline
                      F Offline
                      Furty
                      wrote on last edited by
                      #11

                      Imagine if someone developed a language where any variable could be of any value type - now that would be just silly, but at least your scenario would work :)

                      1 Reply Last reply
                      0
                      • H hzs

                        Your solution Ista wrote: public static string operator + ( string s1, string s2 ) { return (Int32.Parse(s1) + Int32.Parse(s2)).ToString(); } doesn't work...I've had already tried it. The compiler generates an error: One of the parameters of a binary operator must be a containing type". So the + operator can't be overloaded in this way.

                        I Offline
                        I Offline
                        Ista
                        wrote on last edited by
                        #12

                        This is the class public class Class1 { public string s; public Class1() { // // TODO: Add constructor logic here // } public Class1( string stype ) { s = stype; } public override string ToString() { return s; } public static string operator + ( Class1 s1, Class1 s2 ) { string s1s = s1.ToString(); string s2s = s2.ToString(); return (Int32.Parse(s1s) + Int32.Parse(s2s)).ToString(); } } in your form type private void button1_Click(object sender, System.EventArgs e) { Class1 c = new Class1("12"); Class1 c1 = new Class1("20"); string s = c + c1; MessageBox.Show(s); } its rough but works I'm not an expert yet, but I play one at work. Yeah and here too.

                        1 Reply Last reply
                        0
                        • H hzs

                          I've decided to continue using my Add() method. However your point about the "abc" string; since I would be converting the string to an int in my overloaded method, I'd get an error in case "abc" were used; so to avoid this I'd check that the user only enters numeric data. that out of the way, I'd still like to know how to overload + for string or int. (just curios). thanks....hasan

                          I Offline
                          I Offline
                          Ista
                          wrote on last edited by
                          #13

                          actually it would equal zero but god if I was maintaining that could I would be throwing punches I mean really int32.Parse() is very short to right I'm not an expert yet, but I play one at work. Yeah and here too.

                          1 Reply Last reply
                          0
                          • H hzs

                            Hmm...I believe you're right about the maintinence...overloading would cause a lot of confusion so I guess I'll just use my Add & Sub functions. However you've mentioned that "although the language might allow you to do what you want, do you really want to do it?" and I'm curious how does the languge allow me to do what I want i.e how does it allow me to overload +, - operators etc. for primitive datatypes like int and sting. Hasan P.S. The part about going home at 5 went straight to my heart :-D

                            I Offline
                            I Offline
                            isarfraz
                            wrote on last edited by
                            #14

                            P.S. The part about going home at 5 went straight to my heart nice said Muhammad Sarfraz

                            1 Reply Last reply
                            0
                            Reply
                            • Reply as topic
                            Log in to reply
                            • Oldest to Newest
                            • Newest to Oldest
                            • Most Votes


                            • Login

                            • Don't have an account? Register

                            • Login or register to search.
                            • First post
                              Last post
                            0
                            • Categories
                            • Recent
                            • Tags
                            • Popular
                            • World
                            • Users
                            • Groups