Monday, August 3, 2009

Mutable vs Immutable

Why string is immutable and StringBuilder is mutable ?
string builder is mutable .Ie it is pure reference type.The following example the 'foo' is passed as a reference type .So the output is helloanish:
E.g:
class Program
{
static void Main(string[] args)
{
StringBuilder y =new StringBuilder();
y.Append("hello");

Program p = new Program();
p.foo( y);
Console.WriteLine(y );
}

void foo(StringBuilder sb)
{
sb .Append("anish:");
}
}

Stirng is immutable .In some ways it to be value types .These are known as immutable .The following example the 'foo' is passed is a string but this act as a value type .So the output is 'hello'

E.g:

class Program
{
static void Main(string[] args)
{
string y =string.Empty;
y="hello";

Program p = new Program();
p.foo( y);
Console.WriteLine(y );
}

void foo(string sb)
{
sb +="anish:";
}
}

Note : note only string .Some of the other types also.

Rather than creating a new storage location for the function member declaration,the same storage location can be used with the help of ref type.


E.g : class Program
{
static void Main(string[] args)
{
string y ="";
y="hello";

Program p = new Program();
p.foo(ref y);
Console.WriteLine(y );
}

void foo(ref string sb)
{
sb="anish:";
}
}

Output is not hello,its anish

Out type :Same a ref .The thing is that initially the variable is unassigned.

0 comments:

 
Counter