Is there any difference between the use of {0} and + as they both are doing the same work of printing the length on the screen:
Console.WriteLine("Length={0}", length);
Console.WriteLine("Length=" + length);
In your trivial example there's no difference. But there are very good reasons to prefer the formatted ({0}) option: it makes localization of international software much, much easier, and it makes editing your existing strings by third parties much easier.
Imagine for example you're writing a compiler that produces this error message:
"Cannot implicitly convert type 'int' to 'short'"
Do you really want to write the code
Console.WriteLine("Cannot implicitly convert type '" + sourceType + "' to '" + targetType + "'");
? Good heavens no. You want to put this string into a resource:
"Cannot implicitly convert type '{0}' to '{1}'"
and then write
Console.WriteLine(FormatError(Resources.NoImplicitConversion, sourceType, targetType));
Because then you have the freedom to decide that you want to change that to:
"Cannot implicitly convert from an expression of type '{0}' to the type '{1}'"
Or
"Conversion to '{1}' is not legal with a source expression of type '{0}'"
These choices can be made later, by English majors, without requiring changes to the code.
You can also translate those resources into other languages, again without changing the code.
Start always using formatting strings now; when you need to write localizable software that uses string resources properly, you'll already be in the habit.
The second line will create a string and print the string out.
The first line will use composite formatting, like string.Format.
Here are some good reasons to use composite formatting.
There is a difference.
ex:
Console.WriteLine("the length is {0} which is the length", length);
Console.WriteLine("the length is "+length+" which is the length");
+ concatenates two strings, {0} is a placeholder for a string to be inserted.
{n} is a placeholder which can be used with multiple options. where n is a number
In your example it would make a difference and the end result would be same that is concatenation of two string. However in something like
var firstName = "babba";
var lastName ="abba";
var dataOfBirth = new Date();
Console
.Write(" Person First Name : {0} | Last Name {1} }| Last Login : {2:d/M/yyyy HH:mm:ss}",
firstName,
secondName,
dateOfBirth);
it provides a easy to read interface with easy formatting
{n} where n >= 0 allows you to substitute values in order of occurrence in the string.
string demo = "demo", example = "example";
Console.WriteLine("This is a {0} string used as an {1}", demo, example);
+ allows you to concatenate two or more strings together.
Console.WriteLine("This is a " + demo + " string used as an " + example);
Related
I'm relatively new to C# and trying to deserialize a string from JSON for this value; ["format"]["tags"]["ENCODER"]
// Manually building the string works fine
string test = (dict["format"]["tags"]["ENCODER"]);
string found_value = "";
const char quote = '\u0022';
string encoder = "[" + quote + "format" + quote + "][" + quote + "tags" + quote + "][" + quote + "ENCODER" + quote + "]";
// Just as a test
encoder = encoder.Replace("\u005c\u0022", "\u0022");
// This Fails
found_value = (dict[encoder]);
It throws an exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll but was not handled in user code
Additional information: The given key was not present in the dictionary.
So I'm sure it's the way I'm passing the encoder string. Probably something really simple but I've spent hours trying various things and become blind to it now.
Thanks in advance
Basically, C# isn't a scripting language, but is a compiled language. This means that there is no equivalent of a javascript eval() function, and strings don't perform the same as the equivalent code string. So the second lookup, you're trying to do this:
dict["[\"format\"][\"tags\"][\"eval\"]")
And it is rightly complaining that your first dictionary there doesn't have a key of the name
"[\"format\"][\"tags\"][\"eval\"]"
Why are you trying to do this in the second way, when the first one works?
Hi I am trying to save text to a text file with some string, e.g. the students name added to it, but I'm a bit stuck
string iName2 = iName;
string text = "The student named {0} needs more work with plurals";
System.IO.File.WriteAllText(#"C:\Users\user\documents\visual studio 2012\Projects\Artificial_Intelligence_Project_3\WindowsFormsApplication1\Info.txt", text);`
I'm assuming iName is the name. String.Format is the method you need:
string text = String.Format("The student named {0} needs more work with plurals", iName);
Unless you need iName2 somewhere else, you do not need it.
Apart from being more readable, String.Format has one advantage over string concatenation with +. It allows you to change the order of substituted text fragments or omit some of them:
string text = String.Format("{0} {1}", a, b);
// changed order within text without changing argument order!
string text2 = String.Format("{1} {0}", a, b);
This is particularly useful if you're doing localization: Different languages have different rules to construct phrases, where the fragments may need to be substituted in different order.
string text = "The student named " + iName2 + " needs more work with plurals";
I've got an array with three elements
string[] cat = new string[3] { "XBox360", "PS3", "Wii" };
then my I basically compare the array agianst a DataTable and do some manipulation under certain conditions. The code that (I didn't write) performs match is this:
drResults = dtResults.Select(String.Format("Cat = '{0}' AND Cat_Entries = '{1}'", category, cat[i]));
The category (Cat) varialble contains a category numbers and Cat_Entries the elements of the cat array. And so in the code I perform operations if the drResult.Lenght > 0.
What I don't understand is what does the code inside Format() do? I'm looking at Microsoft's definition but what throws me off is the "AND". Also are the numbers between curly brackets {} like a sequential index designator that tell the runtime that the category element repalces Zero, and cat[i] replaces One?
All this is of course inside a loop and other code but I don't think it really adds to the question so I left it out.
The Select method takes a piece of SQL and returns rows that match. In this case you are looking for a row where Cat field = '<category>' AND the Cat_Entries field = '<cat[i]>'
The Format function is a better way of creating the string than doing
"Cat = '" + category + "' AND Cat_Entries = '" + cat[i] + '" as the latter is harder to read and is probably slower due to having to create several interim strings.
The {0} and {1} are just place holders representing the variables that you provide, ie.
category and cat[i]. You can reuse each as many times as you like and in any order,.e.g. it would be valid (albeit stupid) to have
String.Format("Cat_Entries = '{1}' AND Cat = '{0}' AND Cat = '{0}'", category, cat[i])
Ive read a few posts on here and the common suggestion is that stringbuilder is the most efficent if joining over three strings.
all variables are other properties.
public string Summary
{
get
{
return Name.Replace("_", " ") + "<strong>[" + Total + " Devices - " + BadCount + " Offline, " + PendingCount + " Pending]</strong>";
}
}
Im joining four, is a simple concatenation suitable or should I ue stringbuilder? Just seems a little overkill.
Use whatever is most readable in this case. Otherwise it's premature optimization.
I would use String.Format:
String result = String.Format("{0}<strong>[{1} Devices - {2} Offline, {3} Pending]</strong>"
, Name.Replace("_", " ")
, Total
, BadCount
, PendingCount);
return result;
Even string concatenation is not that bad since strings are stored in the intern pool. So if you use a string a second time it's not created but the already available reference is used.
So as rule of thumb:
If you're concatenating few strings and the code gets hardly to understand, use String.Format
If you're concatenating few (literal) strings and the code is still readable, use +(string concatenation)
If you're creating strings in a (long) loop with variable strings, use a StringBuilder
Use String.Format
public string Summary
{
get
{
return String.Format(
"{0}<strong>[{1} Devices - {2} Offline, {3} Pending </strong>",
Name.Replace("_", " "), Total, BadCount, PendingCount);
}
}
What am i doing wrong here? I want the users name to be shown in the output as propercase but I cant figure it out.
string proper = this.xTripNameTextBox.Text;
CultureInfo properCase = System.Threading.Thread.CurrentThread.CurrentCulture;
TextInfo currentInfo = properCase.TextInfo;
proper = currentInfo.ToTitleCase(proper);
this.xTripOutputLabel.Text = proper + Environment.NewLine + "The total gallons you would use: " + Output.ToString("0") + Environment.NewLine + "Total amount it will cost you: " + Coutput.ToString("C") + Environment.NewLine +" Your customer number is " + rnd1.Next(1, 1000).ToString();
I have tested the following on an all upper case word at it works:
string proper = "TEST STRING";
CultureInfo properCase = System.Threading.Thread.CurrentThread.CurrentCulture;
TextInfo currentInfo = properCase.TextInfo;
proper = currentInfo.ToTitleCase(currentInfo.ToLower(proper));
// proper = "Test String"
So - change the string to lower case before calling ToTitleCase.
The MSDN documentation does say that a string that is all upper case (such as an acronym) will not be converted and the sample code provided in the post corroborates this.
That's according to spec, quote from the doc: However, this method does not currently provide proper casing to convert a word that is entirely uppercase
http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx
Without testing I'd guess that you could do it by first making it LowerCase and then TitleCase.
Seems right, I am using
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text);
And it's working.
Try to force another culture info.
See Also
How to capitalize the first character of each word, or the first character of a whole string, with C#?