More C# interview questions on strings


Will the following code compile and run?
string str = null;
Console.WriteLine(str.Length);

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;
if(int.TryParse(str,out i))
{
     Console.WriteLine("Yes string contains Integer and it is " + i);
}
else
{
     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.

4 comments:

  1. The first question compiles and runs successfully without throwing any NullReferenceException.

    ReplyDelete
  2. merin 1st question gives error !

    ReplyDelete
  3. string.Empty not .empty

    ReplyDelete
  4. first question throws NullReferenceException error

    ReplyDelete

If you are aware of any other C# questions asked in an interview, please post them below. If you find anything missing or wrong, please feel free to correct by submitting the form below.

 
Disclaimer - Terms of use - Contact Us