Basic C# Interview Questions on strings

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

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

Q : Are string objects mutable or immutable?

Ans : String objects are immutable.

Q : What do you mean by String objects are immutable?

Ans : 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;

// Output: First String Second String

Q : What will be the output of the following code?

Ans : string str1 = "Hello ";
string str2 = s1;
str1 = str1 + "C#";

The output of the above code is "Hello" and not "Hello C#". This is bcos, 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.

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

Ans : 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 new line 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 ""Vankat.""";
//Output: My Name is "Vankat."

Leave a Reply
Name (required)
Email (will not be published) (required)
Web Site

List of Top Hospitals in India