Ignoring that it won't compile, because there is no String constructor which takes no parameters...
String s;
Declares a variable which
can hold a reference to a string instance.
String s = new String();
Declares the variable and assigns an empty string instance to the variable.
It's a bit like a water glass: the first version creates the glass, and the second fills it with a liquid. If you only declare the glass, you can't do anything with it, like drink the liquid, or stir the liquid, or freeze the liquid.
You have to assign (fill) the string (water) instance to the variable (glass) before you can do anything with it.
"My question is:
If i can manipulate both the string values then what's the difference between both types of declaration. i.e. string s; and string s=new string (new char[] {'h'});
I can use all the string function by using string s; only then what's the meaning of
string s=new string(new char[] {'h'});
both are same.
I am asking the difference."
No, you can't.
If you use
String s;
then using any of the string functions on
s
will
a) Not compile because you will get a "Use of unassigned local variable 's'" error,
and
b) Throw an exception: "Object reference not set to an instance of an object."
Both of these are down to
s
being
capable of holding an instance of a string,
but not actually doing so.
When you use any of the forms:
string s = ...
such as
string s = "My String";
string s = new string(new char[] {'M', 'y', ' ', 'S', 't', 'r', 'i', 'n', 'g'});
string s = new string('X', 6);
string s = new string(new char[] {'M', 'y', ' ', 'S', 't', 'r', 'i', 'n', 'g'}, 3, 5);
Then you are assigning a value to the variable, and giving it a reference to a string instance.
The various ways of assigning a value to the variable just give you different options for doing the same thing:
string s = "h";
string s = new string(new char[] {'h'});
string s = new string('h', 1);
will all end up with the same thing:
s
containing a reference to a string instance that contains a single character: 'h'
The different options just let you do things the way your code needs: because a
string
is effectively just an array of
char
values.
In fact it is perfectly legal to say:
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine(s[i]);
}
Or
foreach (char c in s)
{
Console.WriteLine(c);
}
The only thing you can't do is:
s[4] = '$';
because strings are
immutable which means that once created, you cannot change it in any way - just make a copy with a difference in it. (This can be ignored at the moment, but it becomes significant later)