why use string as a value type

Posted by Ray.chayan under C# on 6/28/2010 | Views : 1414 | Status : [Member] | Replies : 1
We know string is reference type. But why we use string as a value type ?
Like in code
string strName= "Amar";

why don't we use like
String strName = new String();
strName = "Amar";

Like the StringBuilder


Posted by: Santoshkumar on: 6/29/2010 [Member] Starter

string :------

The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework.

'string' is the intrinsic C# datatype, and is an alias for the system provided type "System.String". The C# specification states that as a matter of style the keyword ('string') is preferred over the full system type name (System.String, or String).

Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:

String : ------

A String object is called immutable (read-only) because its value cannot be modified once it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification. If it is necessary to modify the actual contents of a string-like object

Difference between string & String :

---------- ------- ------ - ------

the string is usually used for declaration while String is used for accessing static string methods

we can use 'string' do declare fields, properties etc that use the predefined type 'string', since the C# specification tells me this is good style.

we can use 'String' to use system-defined methods, such as String.Compare etc. They are originally defined on 'System.String', not 'string'. 'string' is just an alias in this case.

we can also use 'String' or 'System.Int32' when communicating with other system, especially if they are CLR-compliant. I.e. - if I get data from elsewhere, I'd deserialize it into a System.Int32 rather than an 'int', if the origin by definition was something else than a C# system.

ITS an example:
It is the string literal "Amar" which is given special treatment. There are 6 literal types in c# (Boolean, Integer, Real, Character, String and null). The type of a string literal is string. You can think of the "Amar" literal in your code as being something like

new String(new char[]{'A', 'm', 'a', 'r'});

so you don't really need string literals and now the code would look a lot more like ordinary code written with reference variables. It would be rather tedious to type however, hence we have string literals.

Ray.chayan, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response