1

Hello all I am working on a project for my C# class and am a bit confused I am trying to add objects to an array and then print them to the console to see if they are there but this is not working for me I am completely lost can someone perhaps show me how to go about this code below.

using System;
class CreateTaxPayer
{
    static void Main()
    {
        Taxpayer[] testArray = new Taxpayer[1];
        for (int i = 0; i < testArray.Length; i++)
        {
            Console.Write("Enter the social security number for taxpayer" + (i + 1) + " ");
            testArray[i].SSN = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(testArray[i].SSN);
        }
    }

}


class Taxpayer
{
    public int SSN { get; set; }

}
2
  • 1
    Should be : Console.WriteLine(testArray[i].SSN); Commented Mar 28, 2020 at 8:29
  • I'm picky but you can't "add objects to an array", you can only initialize the array once it's been created Commented Mar 28, 2020 at 8:30

2 Answers 2

2

You are creating the array, but you also have to create the elements of the array. Like this:

testArray[i] = new Taxpayer();
testArray[i].SSN = Convert.ToInt32(Console.ReadLine());
Sign up to request clarification or add additional context in comments.

1 Comment

omg lzydrmr you are a god I literally have been trying to figure this out for an hour THANK YOU!!!!!!!
0
using System;

    namespace ConsoleApp1

{
    class Program
    {
        static void Main(string[] args)
        {
            Taxpayer[] testArray = new Taxpayer[1];
            for (int i = 0; i <testArray.Length; i++)
            {
                Console.Write("Enter the social security number for taxpayer" + (i + 1) + " ");
                testArray[i] = new Taxpayer();
                testArray[i].SSN = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine(testArray[i].SSN);
            }
        }
    }

    class Taxpayer
    {
        public int SSN { get; set; }

    }
}

1 Comment

This would have been a better answer if you explained what you changed and why

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.