Category 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

Basic Difference between ArrayList and List

Lets find out some important differences for two collection types – ArrayList & List<T> , both are designed / exist in framework for grouping the objects together and perform various operations on them as per our requirments.

ArrayList –

1) Namespace System.Collections contain ArrayList ( This namespace is added by default when we we creat any aspx page in C#)

2) Create ArrayList :

ArrayList stringArrayList = new ArrayList();

Here we dont need to specify object type arraylist going to contain,store different type of objects/items/

3) In ArrayList each item is stored as an Object so while reteriving we can get object only.

4) It is like Array of Objects.


List<T> –

1) Namespace System.Collections.Generic List<T> ( we need to add namespace if we want to use Generic Types)

2) Create List<T>:

List<string> stringList = new List<string>();

i.e.

List<type> nameOfList = new List<type>(); & type means object type which List<T> going to hold.

3) In List<T> , it can hold/contain only type of object which is mentioned while initialising the List<T>

Just like in above example stringList will only contain object of type string, the type supplied as generic parameter.

4) It is newly added in .Net 2.0 & onwards, fast processing no need of casting explicitly.

Lets see one example.

string first = “First String”;

string second = “Second String”;

int firstInt = 1;

int secondInt = 2;

ArrayList stringArrayList = new ArrayList(); // No need to specify the object type,can store anything.

stringArrayList.Add(first); // string type

stringArrayList.Add(second); // string type

stringArrayList.Add(firstInt); // Can contain any type so no problem in storing int


List<string> stringList = new List<string>(); // Need to specify the object type, will contain only string types.

stringList.Add(first);

stringList.Add(second);

1) Lets consider Case :

stringList.Add(firstInt); // adding int in string type List.

we will get the exceptions below as List need to contain only string types. others are not allowed.

1) ‘The best overloaded method match for ‘System.Collections.Generic.List<string>.Add(string)’ has some invalid arguments’

2) ‘Argument ‘1’: cannot convert from ‘int’ to ‘string’

2) Lets consider another case :

string abcd = stringArrayList[1];

Suppose if we try to get an ArrayList item without using the casting then we can get following exception, as arraylist contain Objects only we need to cast as pre our requirments.

We will get Exception –

‘Cannot implicitly convert type ‘object’ to ‘string’. An explicit conversion exists (are you missing a cast?)’

We can avoid it as

string abcd = stringArrayList[1].ToString(); // Needs casting ,memory overhead.