Sunday 20 October 2013

C# interview question string reference type basics

String data type

String is a reference data type in C# .NET framework. Since it is a reference type in .NET framework it has to be with new keyword or by initializing as a literal by providing a value. The keyword string (s in small case) is an alias for String (S in capital case). Both the types string and String are same.

Comparison

When two string variables are compared, the comparison happens between the content to which the variables store reference. C# doesn't compare the references but instead compares the values to which the string variables hold reference. Thus the operators == and != both carry out intended comparison. The Equals method in string class also performs comparison between two string types. The default Equals method performs case-sensitive and culture-insensitive comparison. Other overloads of Equals method provide desired case and culture based comparison.

Immutability/Immutable

Strings in C# .NET are immutable i.e. once string object is created, its contents cannot be changed. In the below example, first we create a initialize a string variable with certain value. The effect of this is that an object with the value "hello" is created on heap and its reference gets assigned to the variable myStr. In the second line, when we assign new value to myStr by appending "world", a new object with the value "helloworld" is created and returned back. Thus myStr now has reference to a new object with new value. The previous object which contained value "hello" is now not used in any variables and so will be cleaned by GC.

string myStr = "hello";
myStr = myStr + "world";

More reading:
  1. Check out what is String.Intern
Hope this is useful.

No comments:

Post a Comment