C# how to add parameters to a string with braces at the beginning?

It's not logical way, you are defining parameter in LoginUrl not in BaseAddress, so it's working correctly

If you want it work logicaly do it that way:

public const string BaseAddress = "http://test.i-swarm.com/i-swarm/api/v1/{0}";
public const string LoginURL = "sessions";

string.Format is replacing {0} with first parameter, so it will now work like you want it to work.


string str = string.Format(LoginURL, BaseAddress); //Is this the correct way?

Yes, that is the correct way. Although it doesn't follow the usual pattern people use. Please read the documentation for the function located here: http://msdn.microsoft.com/en-us/library/system.string.format.aspx

The first argument is the Format, the second are the arguments/replacement values. Assuming you want to maintain a constant format, that is usually a hardcoded in the argument as such:

string str = string.Format("{0}sessions", BaseAddress);

Being as it seems the base address is normally more consistent (but may still be variable) an approach such as the following may be better:

public const string BaseAddress = "http://test.i-swarm.com/i-swarm/api/v1/";
public const string LoginURL = "sessions";
string str = string.Format("{0}{1}", BaseAddress, LoginURL);

If your end-goal is just URL combination rather than an exercise using string.Format, the following may still be a better approach:

Uri baseUri = new Uri("http://test.i-swarm.com/i-swarm/api/v1/");
Uri myUri = new Uri(baseUri, "sessions");

That way you don't have to worry about whether or not a separator was used in the base address/relative address/etc.


There is no logical way, there's just one way to comply to how String.Format works. String.Format is defined so that the first parameter contains the string into which parameters will be inserted, then follows a list of the parameters.

If you define the strings like you do, the only correct way is

string str = string.Format(LoginURL, BaseAddress);

It would be more intuitive, however, if the BaseAddress was the format string:

public const string BaseAddress = "http://test.i-swarm.com/i-swarm/api/v1/{0}";
public const string LoginURL = "sessions";

So you could write

string str = String.Format(BaseAddress, LoginURL);

Yes the correct way is:

string str = String.Format(LoginURL, BaseAddress);

The format string should always be the first parameter.

Though I feel that:

string str = String.Format("{0}sessions", BaseAddress);

Is more readable.