String Interview Questions and Answers in C#

String Interview Questions and Answers in C#

In this article, I am going to discuss the most frequently asked String Interview Questions and Answers in C#. Please read our previous article where we discussed the most frequently asked Data Types Interview Questions and Answers in C#. As part of this article, we are going to discuss the following String Interview Questions and Answers in C#.

  1. Why should you override the ToString() method?
  2. What is the difference between string keyword and System.String class?
  3. Are string objects mutable or immutable in C#?
  4. What do you mean by String objects are immutable?
  5. What is a verbatim string literal and why do we use it?
  6. How do you create empty strings in C#?
  7. What is the difference between System.Text.StringBuilder and System.String?
  8. How do you determine whether a String represents a numeric value?
  9. What is the difference between int.Parse and int.TryParse methods?
Why should you override the ToString() method? 

All types in .Net inherit from the System.Object directly or indirectly. Because of this inheritance, every type in .Net inherits the ToString() method from System.Object class. Consider the example below.

String Interview Questions and Answers in C#

In the above example Number.ToString() method will correctly give the string representation of int 10, when we call the ToString() method. If we have a Customer class as shown in the below example and when we call the ToString() method the output does not make any sense. Hence we have to override the ToString() method, that is inherited from the System.Object class.

public class Customer
{
    public string FirstName;
    public string LastName;
}
public class MainClass
{
    public static void Main()
    {
        Customer C = new Customer();
        C.FirstName = "David";
        C.LastName = "Boon";
        Console.WriteLine(C.ToString());
    }
}

The code sample below shows how to override the ToString() method in a class, that would give the output you want.

public class Customer
{
    public string FirstName;
    public string LastName;

    public override string ToString()
    {
        return LastName + ", " + FirstName;
    }
}
public class MainClass
{
    public static void Main()
    {
        Customer C = new Customer();
        C.FirstName = "David";
        C.LastName = "Boon";
        Console.WriteLine(C.ToString());
    }
}

Conclusion: If we have a class or a struct, make sure you override the inherited ToString() method.

What is the difference between string keyword and System.String class? 

string keyword is an alias for System.String class. Therefore System.String and string keyword are the same, and we can use whichever naming convention we prefer. The String class provides many methods for safely creating, manipulating, and comparing strings.

Are string objects mutable or immutable? 

String objects are immutable.

What do you mean by String objects are immutable?

String objects are immutable means they cannot be changed after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object. In the following example, when the contents of s1 and s2 are concatenated to form a single string, the two original strings are unmodified. The += operator creates a new string that contains the combined contents. That new object is assigned to the variable s1, and the original object that was assigned to s1 is released for garbage collection because no other variable holds a reference to it.

string s1 = "First String ";
string s2 = "Second String";

// Concatenate s1 and s2. This actually creates a new
// string object and stores it in s1, releasing the
// reference to the original object.

s1 += s2;
System.Console.WriteLine(s1);

// Output: First String Second String
What will be the output of the following code? 
string str1 = "Hello ";
string str2 = s1;
str1 = str1 + "C#";
System.Console.WriteLine(s2);

The output of the above code is “Hello” and not “Hello C#”. This is because, if you create a reference to a string, and then “modify” the original string, the reference will continue to point to the original object instead of the new object that was created when the string was modified.

What is a verbatim string literal and why do we use it? 

The “@” symbol is the verbatim string literal. Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths. Because verbatim strings preserve newline characters as part of the string text, they can be used to initialize multiline strings. Use double quotation marks to embed a quotation mark inside a verbatim string. The following example shows some common uses for verbatim strings:

string ImagePath = @"C:\Images\Buttons\SaveButton.jpg";
//Output: C:\Images\Buttons\SaveButton.jpg

string MultiLineText = @"This is multiline
Text written to be in
three lines.";
/* Output:
This is multiline
Text written to be in
three lines.
*/

string DoubleQuotesString = @"My Name is ""Pranaya.""";
//Output: My Name is "Pranaya."
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?

Objects of type StringBuilder are mutable whereas objects of type System.String is immutable. As StringBuilder objects are mutable, they offer better performance than string objects of type System.String. The 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 whereas TryParse returns false and does not throw an exception if parsing fails. Hence TryParse is more efficient than Parse.

In the next article, I am going to discuss the most frequently asked Delegates Interview Questions and Answers in C#. Here, in this article, I try to explain most frequently asked String Interview Questions and Answers in C#. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *