Click here to Skip to main content
16,018,264 members
Please Sign up or sign in to vote.
2.52/5 (6 votes)
See more:
C#
static void Main(string[] args)
        {
             string res;

            for (int i = 1; i <= 4; i++)
            {
                if (i == 1) res = "1";
                else

                     res = "" + i + res + i;//error in -res- in this statement

                    Console.WriteLine(res);

            }
        }
Posted
Comments
Richard MacCutchan 26-Oct-14 9:15am    
And?
PIEBALDconsult 26-Oct-14 10:06am    
And look in to System.String.Format

You made two big mistakes here.

First, all local variable should be initialized (for type members, initialization by default is used).
You would need to initialize if as string res = string.Empty; but this is not a solution yet.

Your second big mistake is repeated concatenation using the same string. You should never do it. Why? Because strings are immutable. None of the string functions modify a string, they all create a brand-new string. You never concatenate anything of the same object. Concatenation creates a brand-new string object and copies all the data from two concatenating strings. Many intermediate objects are created; and data is moved back and forth. This is bad for performance.

So, you need to use the mutable representation of string, code System.Text.StringBuilder. It is initialized through constructor:
C#
System.Text.StringBuilder sb = new System.Text.StringBuilder(); // empty
// and so on...


[EDIT]

Also, I forgot to mention that you "concatenate" integer with string (in fact, implicit ToString() call creates a string; than two strings are concatenated). Even though it works, I agree with Maciej (please see our discussions in comment and in comments to his Solution 4): this is a pretty bad practice. The StringBuilder.Append(int) would also work.

When you explicitly use int.ToString, you can control the format of the string output (there are many ToString methods for all types, with different parameters controlling output format). Besides, it makes your code more explicitly showing what is done.

—SA
 
Share this answer
 
v2
Comments
Maciej Los 26-Oct-14 14:51pm    
+5! Agree: string is immutable.
Although, i still disagree with your comment to my answer (big mistakes). Is it bad to pointed out OP to convert integer to string to enable concatenation?
As you know, below code will compile:
int i = 0;
StringBuilder sb = new StringBuilder();
sb.Append(i);

But is it good programming practice to add integer value this way? I could say, your answer is incomplete. Does it make your answer a big mistake? No!
Even if my answer does not contain information about 'string is immutable', does it make it wrong? Don't think so...
Got my point of view?
Sergey Alexandrovich Kryukov 26-Oct-14 15:02pm    
Oh, oh... Not this point... I did not mean such thing. I already added another comment in the discussion over your answer and wrote that I agree: it would not be a good practice, not in any .NET language, even in VB.NET.
Here, I just added this point to my answer, to have it all in one piece and avoid any confusions about it.
—SA
Maciej Los 26-Oct-14 15:14pm    
Thank you, Sergey.
Sergey Alexandrovich Kryukov 27-Oct-14 0:02am    
Thank you.
—SA
Robert Welliever 27-Oct-14 2:59am    
Whipping out StringBuilder for four iterations of a loop with a few concatenations is not faster or more efficient. Reassigning the immutable strings actually is in this case.
Try :
C#
...
string res = ""; // set it to blank
...
 
Share this answer
 
Comments
Maciej Los 26-Oct-14 10:10am    
Mehdi, please read my comment to the solution 1 and see my answer too ;)
Sergey Alexandrovich Kryukov 26-Oct-14 13:31pm    
I advice to use string.Empty instead of "". This way, one can have most files with no single ", such code is easier to support.
—SA
Sergey Alexandrovich Kryukov 26-Oct-14 13:50pm    
First, string.empty should be used; it's really good to avoid "". Please see my comment to Solution 4.

And this is not the only problem. Please see my Solution 5.

—SA
Few things:
1) You need to properly set string variable:
C#
string res = string.Empty;

2) You can't add string to integer value or cancatenate both this way:
C#
res = "" + i + res + i;

You need to convert it and concatenate:
C#
res = "" + i.ToString() + res + i.ToString();

or via using String.Concat method[^].
 
Share this answer
 
v2
Comments
Mehdi Gholam 26-Oct-14 10:28am    
Technically when the left of a + will auto convert to the right of the + so the ToString() is not needed and the CLR will auto convert to string.

This has the added value of if the right is null then you don't get an exception -> string s = "" + null; // = ""
Maciej Los 26-Oct-14 10:32am    
Technically, yes, but is it good programming practice? Please, read Kornfeld's comment to the solution 1.
Sergey Alexandrovich Kryukov 26-Oct-14 13:47pm    
Right, it would be a bad programming practice. This is acceptable in Javascript, but even in VB.NET I would recommend to avoid it.
—SA
Sergey Alexandrovich Kryukov 26-Oct-14 13:45pm    
Maciej,

Unfortunately, this time you made too many big mistakes for this post to survive. Let's see

"string" can be and should be used. The language is case-sensitive, but in language, "string" is the alias of System.String (int is alias of System.Int32, uint — if System.UInt32, and so on). These aliases can be and should be used; they are part of the language, not just of BCL.

string.Empty should be used. There is no string.Empty(). This is a readonly public field.

You recommended to use repeated concatenation, as OP is already doing. This is bad. Strings are immutable. For efficient repeated concatenation, System.Text.StringBuilder must be used, nothing else. I explained it in Solution 5; please see.

I would really advise you to remove this bad answer.

—SA
Maciej Los 26-Oct-14 14:02pm    
Agree only with first note, but... If string is alias for System.String, which represents string in Unicode characters, is it wrong to use it (technically)? Disagree with others. Please, read my answer again. I recommend OP to convert integer to string or use String.Concat method. Yes, StringBuilder class is very useful in this case.
Simply by:
C#
string res= "";

And yes, also I feel this is very strange, because e.g. int does not have this behaviour.

[EDIT]
I was wrong, also int does Show this behaviour (I'm c++ damaged, but does not excuse anything. http://stackoverflow.com/questions/6032638/default-variable-value[^]
[/EDIT]
 
Share this answer
 
v4
Comments
Maciej Los 26-Oct-14 10:09am    
Bruno, please read my comment to the solution 1 and see my answer too ;)
[no name] 26-Oct-14 10:35am    
I read it and voted my 5. I was too much fixed on initialisation Problem. But it triggered me to think more about these things. I basically work with c++ (embarcadero, former borland). String was a thing which I always assumed if I instantiate it, that it is simply an empty string. On the other hand e.g. int I always initialized it explicitly. Now I'm really asking me why I assumed all the time, that string should be empty by default...maybe because if I instantiate any class I assume the class is ready to go. I do not like to distinguish between simple and complex types. It becomes too much philosophics ;)
Maciej Los 26-Oct-14 10:39am    
Thank you, Bruno.
Short conclusion: C++ is not the same as C# ;)
[no name] 26-Oct-14 10:48am    
So it is. Please tell next time you have dinner with Bill Gates that I'm still missing a deterministic destructor for c# ;)
Kind regards, Bruno
Maciej Los 26-Oct-14 10:52am    
Who is Bill Gates? I don't know Him ;)
:laugh:
Rather than Bill, i prefer beautiful women (as my wife is) ;)
I think I'll join the party:
C#
private string buildIt(int n)
{
    string temp = "1";

    var sb1 = new StringBuilder(temp);

    var sb2 = new StringBuilder();
    sb2.AppendLine(temp);

    for (int i = 2; i <= n; i++)
    {
        sb1.Replace(temp, i + temp + i);
        temp = sb1.ToString();
        sb2.AppendLine(temp);
    }

    return sb2.ToString();
}

// sample call:
string result = buildIt(4);
 
Share this answer
 
C#
static void Main(string[] args)
        {
             string res="";
 
            for (int i = 1; i <= 4; i++)
            {
                if (i == 1) res = "1";
                else
 
                     res = "" + i + res + i;//error in -res- in this statement

                    Console.WriteLine(res);
 
            }
        }
 
Share this answer
 
hello dear !


if your loop iteration is more than ten times you use StringBuilder
else you can use
C#
string str= string.Empty;


StringBuilder sb=new Stringbuilder();
sb.append(vlaue);

OR

//its better than str="";

string str= string.Empty;


string str="";
 
Share this answer
 
C#
static void Main(string[] args)
        {
             string res="";

            for (int i = 1; i <= 4; i++)
            {
                if (i == 1) res = "1";
                else

                     res = "" + i + res + i;
                    Console.WriteLine(res);

            }
        }
 
Share this answer
 
v2
Comments
Maciej Los 26-Oct-14 10:04am    
You can't add string to integer values! You can't concatenate both this way!
Kornfeld Eliyahu Peter 26-Oct-14 10:24am    
In fact adding strings and int is NOT a compile time error (and that makes it more dangerous), as compiler will handle the automatic type convert fro those types, but at run-time the value of the strings can make such an addition a disaster!!!
[no name] 26-Oct-14 10:44am    
Sorry, I can't vote a comment, but this comment is worth more then a five ;)
Regards, Bruno
Kornfeld Eliyahu Peter 26-Oct-14 10:45am    
Thank you...
Sergey Alexandrovich Kryukov 26-Oct-14 13:49pm    
First, string.empty should be used; it's really good to avoid "". Please see my comment to Solution 4.

You recommended to use repeated concatenation, as OP is already doing. This is bad. Strings are immutable. For efficient repeated concatenation, System.Text.StringBuilder must be used, nothing else. I explained it in Solution 5; please see.

—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900