Pages

Friday, May 10, 2013

string in c#

Strings are character arrays in C# 
Strings are reference types in C#.
Strings are immutable
Methods that act on a string will always produce a new string 
 

sample code:

public partial class _Default:System.Web.UI.Page
 
{
 
    protected void Page_Load(object sender,EventArgs e)
 
    {
 
           string s1="Hello";  //Assume it is stored at address 0x222
 
           s1=s1+"Hi";         //Again  it is stored at address 0x333
 
           Response.Write(s1); 
 
     }
 
} 
explanation:
   Above code shows that s1 is string which we can say it is a character array
-s1 is stored in stack and it is pointing to some location in heap 
where Hello is stored,assume thatsome memory address in heap 
such as 0x222 contains string Hello.
-Now again look at this line <b>s1=s1+"Hi",
here s1 now pointing to different memory address say at address 0x333.
So following above code we now can say that s1 at last contains address 0x333.
Any operation of the string will always produce a new string.
So, to eliminate this problem we can use String builder.
 

String Builder:

  >String Builder is a class which is present in System.Text namespace.
>String Builders are mutable.
>When we want to store data in a string but later we wanted to modify data present in a string 
>we have to use string builder.
Sample code:
     using System.Text;

public partial class _Default:System.Web.UI.Page

{

    protected void Page_Load(object sender,EventArgs e)

    {

            StringBuilder sb=new StringBuilder("Hey");

            sb.Append("Whats Up!");

           Response.Write(sb.ToString());

    }

}
 Explanation:-
Here string data "Hey" will be allocated somewhere in the memory and 
when we try to append some other string
"Whats Up!" to the existing string "Hey" the new string will be appended 
to the existing string in the same memory location where "Hey" is present,
it means we can able to change the content of a string
by using StringBuilder or StringBuilders are mutable.

Sample Code:

public partial class String_buid : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string s1 = "palle";
        s1 = s1 + "tech";
        String_buid sb = new String_buid();
        sb.append("palle");
        sb.append("palle");
    }
}

// It is a class in C# or It is mutable(u can change the content of string ussing string Builder)

 

No comments:

Post a Comment