I have come across a problem upon viewing some tutorials on C# since I just started learning this language recently. I had a problem where once I had reversed a string I had to make use of new string in order to store its actual value in a different varible.
Why is the use of 'new string()' needed? In different programming languages I have never come across the need of using 'new string()'. Thanks in advance :)
//C#
char[] reversedName = name.ToCharArray();
Array.Reverse(reversedName);
string result = new string(reversedName);
String
is a class like other classes in any Object oriented programming language and we can create object of it using new
keyword like we would do for creating object of any type.
In your specific scenario above you have a char
array and String
class have a constructor overload which take char[]
as input and create a String
. So you call the constructor using new String
.
So what is happening is you said to create an object of type string using char[]
which is provided in the constructor of it.