More C# interview questions on strings
Will the following code compile and run?
string str = null;
The above code will compile, but at runtime System.NullReferenceException will be thrown.
How do you create empty strings in C#?
Using string.empty as shown in the example below.
string EmptyString = string.empty;
What is the difference between System.Text.StringBuilder and System.String?
1. Objects of type StringBuilder are mutable where as objects of type System.String are immutable.
2. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String.
3. StringBuilder class is present in System.Text namespace where String class is present in System namespace.
How do you determine whether a String represents a numeric value?
To determine whether a String represents a numeric value use TryParse method as shown in the example below. If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.
string str = "One";
int i = 0;
Console.WriteLine("Yes string contains Integer and it is " + i);
Console.WriteLine("string does not contain Integer");
What is the difference between int.Parse and int.TryParse methods?
Parse method throws an exception if the string you are trying to parse is not a valid number where as TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse.