C# adding string to another string

Just use the + operator:

variable1 = variable1 + IntToHex(buffer[i]);

You also need to initialise variable1:

string variable1 = string.Empty;

or

string variable1 = null;

However consider using a StringBuilder instead as it's more efficient:

StringBuilder builtString = new StringBuilder();

for (int i = 0; i < 299; i += 2)
{
    builtString.Append(IntToHex(buffer[i]));
}

string variable1 = builtString.ToString();

In C#, simply use a + to concatenate strings:

  variable1 = variable1 + IntToHex(buffer[i]);

But more important, this kind of situation requires a StringBuilder.

    var buffer = new StringBuilder();
    for (int i = 0; i < 299; i += 2)
    {
        buffer.Append( IntToHex(buffer[i]) );
    }

    string variable1 = buffer.ToString();

For loops of 100 or more this really makes a big difference in performance.


&& is the conditional-AND operator.

You can use the + operator for string concatenation, but it's not a good idea to use that within a loop (details).

Either use a StringBuilder:

StringBuilder builder = new StringBuilder(299 * 4); // Or whatever
for (int i = 0; i < 299; i += 2)
{
    builder.Append(IntToHex(buffer[i]));
}
string combined = builder.ToString();

Or potentially use string.Join - it might not be as practical in this case given your looping, but in other cases it would be great. You could still use it here, like this:

string combined = string.Join("", Enumerable.Range(0, 149)
                                       .Select(i => IntToHex(buffer[i * 2])));

Tags:

C#