-10

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);
jazb
  • 5,498
  • 6
  • 37
  • 44
Evilc
  • 23
  • 8
  • 4
    Its use is documented in the [language reference](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/new-operator) – Sir Rufo Jul 30 '19 at 06:27
  • 1
    which "different languages" you refer to? Knowing this it may be easier for us to explain to you the differences. – MakePeaceGreatAgain Jul 30 '19 at 06:29
  • Different languages have different rules, semantics, syntax and constructs. You can seldom base your learning of a new language on another different language. – Some programmer dude Jul 30 '19 at 06:31
  • And just about all decent books and tutorials should have included chapters or sections about how to create objects, which would include the `new` keyword. So either the tutorial you're following is bad, or you skipped some part. – Some programmer dude Jul 30 '19 at 06:32
  • I made use of C and Java – Evilc Jul 30 '19 at 06:32
  • 1
    Java have `new`, used in exactly the same way. The equivalent line in Java would be something like `String result = new String(reversedName);`. – Some programmer dude Jul 30 '19 at 06:33
  • I agree but I never made use of 'new' because without it's use everything performed just right that's why I was confused. So basically making the use of 'new' when creating a new object is always the optimal solution. – Evilc Jul 30 '19 at 06:35

3 Answers3

0

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.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • Understood but what I don't understand is why would you need to create a new object in this case string, why wouldn't it store its actual value right away? Sorry if I am not explaining my question clearly. – Evilc Jul 30 '19 at 06:31
  • 1
    @Evilc strings are immutable. You can't modify a string, you can only create a new string. Note also that `reversedName` is a different object in memory to `name` - you are creating an array based on the characters in the string. – ProgrammingLlama Jul 30 '19 at 06:32
0

You can - as in any other of your mentioned languages - of course also use something like this:

string m = "Hello World". 

However your reversedName is an array of char, which is not convertible to string as is. So the following won´t work:

string myString = "Hello World".ToCharArray();

because ToCharArray - as the name suggests - returns char[], not string and there´s no conversion between the two.

That´s why you need to create a new string using the constructor that accepts an array of char.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
0

The new-Keyword is used to create a new instance of your class.

If you want to assign one value of one type to another type you have to convert it in some way.

There are multiple ways:

  1. Call a Constructor which accepts your input (You did this, because there is a constructor for string which accepts char[])
  2. Use a Cast (No Cast available from char[] to string)
  3. Use a Convert-Method (No available for converting values to string as far a I know)

Here an example-class which implements explicit and implicit casts (Which System.String does not):

class MyString
{
    private string stringValues;

    // Constructors
    public MyString(char[] charArray) { stringValues = new string(charArray); }
    public MyString(string str) { stringValues = str; }
    public MyString() { }

    // ToString for writing to console
    public override string ToString() { return stringValues; }

    // Operator to concat "MyStrings"
    public static MyString operator +(MyString a, MyString b) { return new MyString(a.ToString() + a.ToString()); }

    // Implicit Cast-operator string to MyString
    public static implicit operator MyString(string str) { return new MyString(str); }

    // Explicit Cast-operator char-array to MyString
    public static explicit operator MyString(char[] str) { return new MyString(str); }
}

internal static void Main(string[] args)
{
    MyString tmp = new MyString("Initialize by constructor with parameter string");
    Console.WriteLine(tmp);

    tmp = new MyString("Initialize by constructor with parameter char-array".ToCharArray());
    Console.WriteLine(tmp);

    tmp = new MyString("x") + new MyString("+") + new MyString("y");
    Console.WriteLine("Use of '+ operator'" + tmp);

    tmp = "Initialize by creating string and using implicit cast for strings";
    Console.WriteLine(tmp);

    tmp = (MyString)("Initialize by creating char-array and using explicit cast for strings".ToCharArray());
    Console.WriteLine(tmp);
}
kara
  • 3,205
  • 4
  • 20
  • 34