Class is a reference types while Struct is a value type.
This means that I do not need to explicitly specify ref for every parameter which is a type of class.
My Question is,
Why do we have to specify a ref keyword for a string type which is basically a type of class ?
Please find the example below
public partial class StringManupulation : Form
{
public StringManupulation()
{
InitializeComponent();
String value = "Hello ";
Concatenate( value );
MessageBox.Show( value );
Concatenate( ref value );
MessageBox.Show( value );
}
/// <summary>
/// Does not work
/// </summary>
/// <param name="value"></param>
public void Concatenate( String value )
{
value = string.Concat( value, "StackOverflow" );
}
/// <summary>
/// Works!
/// </summary>
/// <param name="value"></param>
public void Concatenate( ref String value )
{
value = string.Concat( value, "StackOverflow" );
}
}
System.Stringis immutable – That means you cannot change the content of string once it is assigned. You may trySystem.Text.StringBuilder(mutable object) instead ofSystem.Stringclass.Have a look at Strings in C# and .NET and article – chapter from C# in Depth.
Quote to Jon Skeet