SitePoint Sponsor

User Tag List

Results 1 to 7 of 7

Thread: String Concatenation

  1. #1
    SitePoint Zealot
    Join Date
    Dec 2005
    Posts
    153
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    String Concatenation

    Hello,
    I have a simple question. This code for example

    Code:
    int a = 1;
    string b = "cool" + a;
    do I have to include the '+' symbol to concat a literal and a variable? I am pretty sure there is a simpler way to do this. Let me know your thoughts. Thanks

  2. #2
    Chopped Liver bronze trophy imaginekitty's Avatar
    Join Date
    Aug 2007
    Location
    Pennsyltucky
    Posts
    1,493
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by luke101 View Post
    ... I am pretty sure there is a simpler way to do this. ...
    Yeah, i know. Hitting that + key just takes the wind right out of me.

  3. #3
    SitePoint Zealot
    Join Date
    Dec 2005
    Posts
    153
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So you are saying there is not an easier way? It will make the code a whole lot easier to read if the '+' symbol was not there. In PHP you do not need symbols to concat variables and literals and it makes it so much easier to read.

  4. #4
    SitePoint Wizard
    Join Date
    Feb 2007
    Posts
    1,273
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The concatenation operator is nessecary in C#.

    But let us completely ruin your day: Your code will not work, as you are concatenating a string and an int. You have to somehow convert the int to a string, e.g. like: string b = "cool" + a.ToString();

  5. #5
    SitePoint Zealot snomag's Avatar
    Join Date
    Apr 2006
    Location
    Reading
    Posts
    141
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Morning,

    I might be wrong, but for some reason I think when you concatenate to a string, the ToStrint() method's automatically called.

  6. #6
    SitePoint Zealot Lars's Avatar
    Join Date
    Jun 2000
    Location
    Denmark
    Posts
    113
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    How about:

    Code Csharp:
    b = String.Format("cool {0}", a.ToString());

  7. #7
    SitePoint Addict
    Join Date
    Feb 2000
    Location
    Vilnius, Lithuania
    Posts
    203
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Another option is to use
    Code Csharp:
    string b = String.Concat("cool", a);

    This way you can get away without using ToString() (AFAIR) but it doesn't get any easier
    SPAW Editor v.2 - web based wysiwyg editor for PHP and ASP.NET.
    Opera and Safari support, tabbed interface, floating toolbar...

Bookmarks

Posting Permissions

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