A String question

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I need to make the following sentence to be a string variable and how should
I do it?

server=SQL;database=SQLTest;user id=test;password=1234

private static string str= "server=SQL" + ";" + "database=SQLTest" + ";" +
"user id=test" + ";" + "password=1234";

It shows many errors.

Thanks
 
It's suggested to avoid string concatenations if you are concatenating 5 or
more strings. If you need to concatenate a lot of strings or a number of
strings that you can't predict you should use StringBuilder class. But in
this case i suggest you to take a look at the Concat method of the String
class.

HTH
 
Hi Tom,

I don't see any immediate errors in your code, but why do you concatenate
when you can simply do

private static string str = "server=SQL;database=SQLTest;user
id=test;password=1234";

You don't say what errors you are getting so I can't help you there (I get
none).
As for connectionstrings, you may use this page for a selection of various
ones:

http://www.connectionstrings.com/
 
It's suggested to avoid string concatenations if you are concatenating 5 or
more strings. If you need to concatenate a lot of strings or a number of
strings that you can't predict you should use StringBuilder class. But in
this case i suggest you to take a look at the Concat method of the String
class.

String concatenations such as the one given are fine - if you're
concatenating several strings in one step, it's more effective to do
that than to use a StringBuilder. It's if you end up creating
intermediate strings that things become inefficient.

In the example given, in fact, the compiler does the concatenation in
advance, so it's just a simple string assignment.
 
Tom said:
I need to make the following sentence to be a string variable and how should
I do it?

server=SQL;database=SQLTest;user id=test;password=1234

private static string str= "server=SQL" + ";" + "database=SQLTest" + ";" +
"user id=test" + ";" + "password=1234";

It shows many errors.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

The code as you've posted it is fine. For example:

using System;

class Test
{
private static string str= "server=SQL" + ";" +
"database=SQLTest" + ";" +
"user id=test" + ";" + "password=1234";

static void Main()
{
Console.WriteLine (str);
}
}

compiles and runs with no problems.
 
Back
Top