CSharpSuzie
CSharpSuzie

Reputation: 287

Object Arrays in Console Application

I want to create an array of users in a console app but cant seem to get it right, can anyone please help, here is my code.

class Program
{
    static void InputUser(User U)
    {           
        Console.WriteLine("Please enter a User:");
        Console.WriteLine("User ID:");
        U.ID = int.Parse(Console.ReadLine());
        Console.WriteLine("Titel:");
        U.Titel = Console.ReadLine();
        Console.WriteLine("Name:");
        U.Name = Console.ReadLine();
        Console.WriteLine("Surname:");
        U.Surname = Console.ReadLine();
        Console.WriteLine("Telephone Number:");
        U.Telephone = int.Parse(Console.ReadLine());
        Console.WriteLine();
    }

    static void Main()
    {
        User[] users = new User[2]
        { 
            InputUser(new User); 
        }           
    }                    
}

Upvotes: 0

Views: 2331

Answers (4)

asawyer
asawyer

Reputation: 17808

InputUser needs to pass the User object by reference (ref keyword) or it needs to return a new instance of User instead of accepting a parameter.

Upvotes: 0

Giuseppe Accaputo
Giuseppe Accaputo

Reputation: 2642

First, change the InputUser method to return a User object which will be constructed using the user's input:

static User InputUser()
{          
    User U = new User();
    Console.WriteLine("Please enter a User:");
    Console.WriteLine("User ID:");
    U.ID = int.Parse(Console.ReadLine());
    Console.WriteLine("Titel:");
    U.Titel = Console.ReadLine();
    Console.WriteLine("Name:");
    U.Name = Console.ReadLine();
    Console.WriteLine("Surname:");
    U.Surname = Console.ReadLine();
    Console.WriteLine("Telephone Number:");
    U.Telephone = int.Parse(Console.ReadLine());
    Console.WriteLine();
    return U;
}

And then call the InputUser method two times, since you're initializing an array of User objects with the size of 2:

static void Main()
{
    User[] users = new User[2]
    { 
        InputUser(),
        InputUser()
    }           
}  

Upvotes: 2

Russ
Russ

Reputation: 4163

Change your main method to something like:

 static void Main() 
    { 
        User[] users = new User[2];

        for (int i=0;i<users.Length; i++) 
        {  
            users[i] = new User();
            InputUser(users[i]);  
        }            
    } 

Upvotes: 1

Wildhorn
Wildhorn

Reputation: 932

User[] users = new User[2]

will just create an array of User, but it doesnt initialize them.

For each of them you need to create a User.

So add a loop after it like this:

        for (int i=0;i<users.Length; i++) 
        {  
            users[i] = InputUser(users[i]); 
        } 

Upvotes: 0

Related Questions