Search code examples
c#return

Returning not working


I dont understand why i cannot access studentinformation from the function getstudentinformation. Here is the code:

static void Main(string[] args)
{
    getstudentinformation();
    string firstname = studentinformation[0];
}

static Array getstudentinformation()
{
    Console.WriteLine("enter the student's first name: ");
    string firstname = Console.ReadLine();
    Console.WriteLine("enter the student's last name");
    string lastname = Console.ReadLine();
    Console.WriteLine("enter student's gender");
    string gender = Console.ReadLine();
    string[] studentinformation = { firstname, lastname, gender };
    return studentinformation;
}

Visual Studio does not recognise the array and when i try to build the code there is this error of not recognising studentinformation.


Solution

  • Your code is wrong. Try this:

    static void Main(string[] args)
        {
            string[] studentInformation = getstudentinformation();
            string firstname = studentinformation[0];
        }
        static string[] getstudentinformation()
        {
            Console.WriteLine("enter the student's first name: ");
            string firstname = Console.ReadLine();
            Console.WriteLine("enter the student's last name");
            string lastname = Console.ReadLine();
            Console.WriteLine("enter student's gender");
            string gender = Console.ReadLine();
            string[] studentinformation = { firstname, lastname, gender };
            return studentinformation;
        }
    

    You were not assigning to any variable the result of getstudentinformation and since the variable that you are trying to access is declared in another scope, you cannot have access to it.