Tag Archives: C# Interview Questions

String Vs StringBuilder …… point by point

1) Namespace :

String class belongs to the System namespace i.e. System.String

StringBuilder class belongs to the System.Text i.e. System.String.StringBuilder

2) Store Location :

String , StringBuilder both being reference types , Stored on Heap memory

3) Mutable/Immutable :

The System.String class is immutable, i.e once created its state cannot be altered. i.e. All .NET stings are immutable. You cannot modify any string at all. All string operations create yet another string.in simple words any change to string causes a runtime to create a new string and abandon old one

Consider the following example:

class MyClass

{

public static void Main() {

string sampleString = “CollectedDotNet”;

sampleString = “Hello World”;

Console.WriteLine(sampleString);

}

}

Output will be: Hello World

In this sample, we have created a string called sampleString. We initially assigned the value “CollectedDotNet”. And then we overwrite its value with “Hello World” , which we got as output. But in the memory 2 string are got created when we createed the string “CollectedDotNet”, this string gets created in the memory, but when we tried to change the value to new values , at that time new string “Hello World” got created in memory and reference got assigned to sampleString.

Lets see another example ,

string s1 = “CollectedDotNet”;

string s2 = s1;

s1 = “Hello World”;

Now what happens is a new string object is created for s1 to point to.Hence, s1 equals “Hello World” , whereas s2 still equals “CollectedDotNet”

Advantages of Immutability:

  • Thread Safety ,

Sharing ,

  • Less error prone

 For StringBuilder,

On contrast with String , StringBuilder class is mutable.

StringBuilder sampleStringBuilder = new StringBuilder(“CollectedDotNet”);

Console.WriteLine(sampleStringBuilder);

sampleStringBuilder = new StringBuilder(“Hello World”);

Console.WriteLine(sampleStringBuilder);

Output will be :

CollectedDotNet

Hello World

In this sample , we have created a string called sampleStringBuilder. We initialized with value “CollectedDotNet”.And then we created new with “Hello World” , in this case no new strings will be created in the memory.

Further Reading Reference :

http://www.codeproject.com/Articles/406046/Why-strings-are-immutable-and-what-are-the-implica

http://forums.asp.net/t/1158680.aspx/1

4) Assigning/Appending String:

You can directly assign a string to string class instance.

e.g.  string sampleString = “CollectedDotNet”;

is Valid for String but not for StringBuilder.

For StringBuilder,

You cannot directly assign a string to StringBuilder instance.

e.g.  StringBuilder sampleStringBuilder = “CollectedDotNet”;

The above line will return the following error on compilation :
“Cannot implicitly convert type ‘string’ to ‘System.Text.StringBuilder'”cannot implicitly convert type

You can assign a string to StringBuilder using the following way

StringBuilder sampleStringBuilder = new StringBuilder(“CollectedDotNet “);

5) Concatenation /Capacity :

String concatenation is done using + operator.

E.g. string sampleString = “Hello”;

sampleString += ” World!!”;

Console.WriteLine(sampleString);

Output : Hello World!!

The same can be achieved using sampleString = sampleString + “ World!!”;

During string concatenation,additional memory will be allocated.You cannot set a limit (specifying how many strings can be concatenated) to a string object using string class In Case for StringBuilder Concatenation is done using Append() Method.

StringBuilder sampleStringBuilder = new StringBuilder(“Hello”);

sampleStringBuilder.Append(” World!!”);

Console.WriteLine(sampleStringBuilder);

Output : Hello World!!

For StringBuilder ,

During string concatenation, additional memory will be allocated if and only if the string buffer’s capacity is reached. You can set a limit to StringBuilder using the property called capacity which will by default have the value 16. You can override it to any number. The maximum value acceptable is equivalent to MaxValue of Int32.  If you feel that you do not want to reserve 16 as the capacity then you can very well redefine it. However the capacity will dynamically grow based on the number of strings that you append.

The StringBuilder dynamically allocates more space when required and increases Capacity accordingly. For performance reasons, a StringBuildermight allocate more memory than needed. The amount of memory allocated is implementation-specific.

Reading References

.net String vs. StringBuilder – concatenation performance

So, when should you use StringBuilder, and when should you use the string concatenation operators?

Refer the following link .. explained nicely

http://yoda.arachsys.com/csharp/stringbuilder.html

Readonly , Const & Static Readonly

I am not here mentioning any new thing , just orgainising this; is one of the most frequently asked questions for entry level .net programmers/developers

Const :

1 A Const variable value is initialized at Compile time and Cant be changed afterwards once value is assigned.

2 A Const variable is initiailized at declaration only cant be changed once initialised.

3 It is to be said that Const variable/member is considered as Static by compiler at time of compilation. but Const cant be declared as static.

4 Constants must be of an integral type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string), an enumeration,   or a  reference to null.

5  Const cant be of type class / structure bcoz both are initialized at runtime ( with new keyword ) & const expected to assign value at compile time.

e.g.

public class MyClass

{

public const double e = 2.71828;  // Need to assign value at the time of declaration.

}

To use a constant outside of the class that it is declared in, you must fully qualify it using the class name.

*****************************************************************************************************************

Readonly :

1 A Readonly variable can be either instance-level or static.

2 A Readonly variable value is initialized at run time and Cant be changed afterwards once value is assigned.

3 A Readonly variable can be initialized at declaration or by code in the constructor, Can have different values depending upon which constructor is getting  called.(Also variable can be modified/initialized at Static Instructor if Variable is static readonly.)

4 A Readonly members cannot be of type enumerations.

e.g.

public class MyClass

{

public readonly double e = 2.71828;

}

OR

public class MyClass

{

public readonly double e; // Can use Default value ,initialization at the runtime.

public MyClass()

{

e = 2.71828;

}

}

The readonly field can be used for runtime constants as in the following example:

public static readonly uint l1 = (uint)DateTime.Now.Ticks;


REF Details : Readonly &   Static

*****************************************************************************************************************

Static Readonly:

1 We can create ‘static readonly’ member when we want member to be accessed without need to create instance of the class.

2 static readonly is generally used if the type of the field is not allowed in a const declaration, or when the value is not  known at compile t ime.

3 For static readonly member we can modify/initialize at Static Instructor.

Note :

1.  I would like to borrow an examples from MSDN Blogs

Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field.  It specifically does not make immutable the object pointed to by the reference.

class Program

{

public static readonly Test test = new Test();

static void Main(string[] args)

{

test.Name = “Program”;

test = new Test();  // Error: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)

}

}

class Test

{

public string Name;

}

On the other hand, if Test were a value type, then assignment to test.Name would be an error.

2. If the readonly member is of type int then.

class Test

{

readonly int testValue;

readonly int testnew = 12;

Test(int TestValue)

{

testValue = TestValue;

}

void ChangeYear()

{

testValue = 10; // Will get compile time error.

testnew = 23; // Will get compile time error.

}

}

we  will get the compiler error message:  “The left-hand side of an assignment must be an l-value”

We will get the same error when we try to assign a value to a constant.