Click here to Skip to main content
14,644,614 members
Rate this:
Please Sign up or sign in to vote.
See more:
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
Rate this:
Please Sign up or sign in to vote.

Solution 5

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:
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
   
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.
   
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.
   
I already explained why "not always faster" is not a great excuse. "A few" is something uncertain here. And I simply cannot understand the second sentence...

—SA
Rate this:
Please Sign up or sign in to vote.

Solution 2

Try :
...
string res = ""; // set it to blank
...
   
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
Rate this:
Please Sign up or sign in to vote.

Solution 4

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

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

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

or via using String.Concat method[^].
   
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.
Sergey Alexandrovich Kryukov 26-Oct-14 14:19pm
   
You already changed Empty() to Empty. It means, you were agree on that item, too. :-)

Alias means that string is exactly the same as System.String. All strings and characters are Unicode in .NET; so this aspect is irrelevant. It is not wrong to use "string". To me, it's even better; you emphasize that you use the same type in its shorter form, considering it as a part of the language. What's wrong with that.

What else do you disagree with and why? How about reading my answer?

Thank you.

—SA
Maciej Los 26-Oct-14 14:59pm
   
Yes, i changed it (String.Epmty()->string.Empty), because it was a 'typing mistake' (of course String has been changed to string with respective to your comment).
I've already read your answer and posted my comment.
Rate this:
Please Sign up or sign in to vote.

Solution 3

Simply by:
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]
   
v4
Comments
Maciej Los 26-Oct-14 10:09am
   
Bruno, please read my comment to the solution 1 and see my answer too ;)
0x01AA 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# ;)
0x01AA 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) ;)
0x01AA 26-Oct-14 10:57am
   
I think you took the right choice!
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
0x01AA 26-Oct-14 14:27pm
   
I know you are responsible for it, but why a string can not be empty by default? Any of "my own" written classes I do not have to assign MyClass.Empty....a noob's meaning ;)

And btw: "You recommended to use repeated concatenation, as OP is already doing". No I did not recommended it. I was only focused on the subject "unassigned".
Robert Welliever 27-Oct-14 3:18am
   
String.Empty is an unnecessary abstraction with no performance advantage or additional readability, and using StringBuilder for string concatenation is not always faster.
   
I appreciate your critical view of things. In principle, you are right. This abstractions is not related to performance. It is related to... abstractions. In practice, this is related to maintainability. You may find it weird, but I find it important to have mass of files without a single " character. I hope you can guess why. In such cases, "" is the only hassle, which would spoil, for example, the check up with the global text search. To me, code text with "" just looks dirty. Again, this is not a very principle thing.

"Not always faster" is not a great excuse. This is, again, a maintenance thing. Say, you have a cycle; and a number of the iterations is a variable. In this value is a small number, even if the StringBuilder is not faster, the time is short; but when the number of iterations becomes bigger, the performance becomes a problem.

—SA
Rate this:
Please Sign up or sign in to vote.

Solution 6

I think I'll join the party:
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);
   
Rate this:
Please Sign up or sign in to vote.

Solution 7

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);
 
            }
        }
   
Rate this:
Please Sign up or sign in to vote.

Solution 8

hello dear !


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


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

OR

//its better than str="";

string str= string.Empty;


string str="";
   
Rate this:
Please Sign up or sign in to vote.

Solution 1

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);

            }
        }
   
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!!!
0x01AA 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
Kornfeld Eliyahu Peter 26-Oct-14 13:55pm
   
Are you sure this post is for me?!
All I stated that this kind of writing is much more dangerous than it looks like, as it does not generate compile time error, but can produce disastrous results...
Sergey Alexandrovich Kryukov 26-Oct-14 14:02pm
   
Sorry, no. My idea was: in this position of the comment reply tree, it will be cause notifications to all participant of this discussion, including the author of the answer. Please forgive me for using your post and disturbing you in this way.
—SA
Kornfeld Eliyahu Peter 26-Oct-14 14:05pm
   
Nothing happened - I just thought that you made a mistake :-) (It's good idea to post on the last and in that way notify all who interested in the topic - I didn't know it works like that but from now I will use it when appropriate, thank you!)
Sergey Alexandrovich Kryukov 26-Oct-14 14:20pm
   
:-)
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100