-1

I am using methods in c#. i returned something but compiler is not printing which i am expecting. It is printing (system.string[]). i dont know why Please help on this.

class Program
{
    static void Main(string[] args)
    {
        string[] sub = subjects();
        Console.WriteLine(sub);
    }
    public static string[] subjects()
    {
        Console.WriteLine("Please Enter How many Subject Do you Want to input");
        int limit = System.Convert.ToInt32(Console.ReadLine());
        string[] Subjects = new string[limit];
        for (int i = 0; i < limit; i++)
        {
            Console.WriteLine("Please Enter Subject Name " + i);
            Subjects[i] = Console.ReadLine();
        }
        return Subjects;

    }
}
apomene
  • 14,282
  • 9
  • 46
  • 72
haris.m
  • 11
  • 3

3 Answers3

5

The reason that Program is printing system.string[] is because class string[] does not override ToString method, so the default one is used and the default ToString returns type name, not the "value" inside type.

You can use for example String.Join method to build one string from array of strings and put given delimiter between each string:

Console.WriteLine(String.Join(", ", sub));
2
Console.WriteLine(sub) 

wont show you anything of value (it prints the sub type), since you are not referencing any value of the sub array, e.g sub[0]. Try this:

foreach (string s in sub)
{
  Console.WriteLine(s);
}
apomene
  • 14,282
  • 9
  • 46
  • 72
-1
Console.WriteLine(String.Join(", ", sub));
paparazzo
  • 44,497
  • 23
  • 105
  • 176
  • 7
    Come on, 30k+ and you're just dumping a line of code? – James Thorpe Feb 22 '17 at 13:51
  • Looks like a succinct answer to the problem. Nothing wrong with that. Are you checking all of Jon Skeet's answers to chide him when he offers a short answer? – duffymo Feb 22 '17 at 13:53
  • 4
    @duffymo A bit of explanation about why the OP is seeing `system.string[]` printed wouldn't go amiss is all I'm saying. – James Thorpe Feb 22 '17 at 13:53
  • The tone of your original comment was different. No need for that, unless you plan to do the same to Jon Skeet. – duffymo Feb 22 '17 at 13:54
  • 1
    @duffymo If _anyone_ posts a code only answer, or just with a "try this" comment, I tend to comment, regardless of rep. It's all the more surprising when high-rep users do it. – James Thorpe Feb 22 '17 at 13:59
  • @JamesThorpe - there are better ways to boost your rep, like answering questions. Sorry, comments like this seem like a waste of time to me. Why not put your "better" answer out there and see who votes it up or down? – duffymo Feb 22 '17 at 14:01
  • 3
    @duffymo I'm not all that interested in boosting my own personal rep anymore - instead I'd rather have high quality Q&A, for the benefit of everyone. – James Thorpe Feb 22 '17 at 14:02