Mitchell Opitz Mitchell Opitz - 18 days ago 7
C# Question

Add to array and return array values - C#

New to coding and this is probably fairly basic, but help would be appreciated.

I believe I have an issue with how I am adding

note2
to
majorScale[]
. Once the block is finished, it returns
System.String[]
rather than the actual array I was expecting.

public static string[] majorScaleOfNote (string tonic)
{
string[] intervals = { "M2", "M3", "P4", "P5", "M6", "M7" };
string[] majorScale = new string[7];
majorScale [0] = tonic;
foreach (string interval in intervals) {
string note2 = intervalUpToNote (tonic, interval);
majorScale[Array.IndexOf (intervals, interval) + 1] = note2;
}

return majorScale;

}


I've narrowed down the problem to something in the
string[] majorScale
. When I run something without that, it produces the correct result. Something like this:

Console.WriteLine (tonic);
string[] intervals = { "M2", "M3", "P4", "P5", "M6", "M7" };
foreach (string interval in intervals) {
string note2 = intervalUpToNote (tonic, interval);
Console.WriteLine (note2);
}


Is there an problem with the way I am adding
note2
to
majorScale
? Or is there another issue? Any help is appreciated!

Answer

The problem is most probably not in this method, but in using a result of method execution in a calling method.

I guess, you later try to Console.WriteLine the contents of its array like this:

string[] result = majorScaleOfNote("M1");
Console.WriteLine(result); 

You cannot output arrays this way.
C# applies .ToString() to all objects in order to get their string representation. Arrays do not have its own ToString() method, which results in the most base class Object's .ToString() being called. It simply does the following:

public virtual String ToString()
{ 
    return GetType().ToString(); 
}

That's why, it outputs its type which results to System.String[].

If you want to output all elements of an array, you could try to iterate through it yourself and output strings one by one:

string[] result = majorScaleOfNote("M1");
foreach (var note in result)
    Console.WriteLine(result); 

or you can use String.Join method, which joins a string using a provided separator:

string[] result = majorScaleOfNote("M1");
Console.WriteLine(string.Join(", ", result));