0

I'm trying to learn programming in general using C# as my first language so please bear with me as I do not know how to exactly asked what I need to ask. Basically I'm following along code from a YouTube video and I hit a brick wall. Here's the entire source code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CoffeeNCodeStructures
{
    public class Program
    {
        public class Person
        {
            public string name;
            public int age;

            public Person(string name, int age)
            {
                this.name = name;
                this.age = age;
            }

            public string PrintPerson()
            {
                return "Name: " + name + " - Age: " + age;
            }
        }
        static void Main(string[] args)
        {
            List<Person> people = new List<Person>();

            for (int i = 0; i < 2; i++)
            {
                Console.WriteLine("Please enter your name: ");
                string name = Console.ReadLine();

                Console.Write("Please enter your age: ");
                int age = Convert.ToInt32(Console.ReadLine());

                people.Add(new Person(name, age));
            }

            foreach (var item in people)
            {
                Console.WriteLine(Person.PrintPerson());
            }

            Console.ReadLine();
        }
    }
}

Visual Studio is throwing me this error

error CS0120: An object reference is required for the non-static field, method, or property 'Program.Person.PrintPerson()'

The issue is in this code block specifically

            foreach (var item in people)
        {
            Console.WriteLine(Person.PrintPerson());
        }

Person.PrintPerson() won't work. What am I doing wrong in the code? I hope this question isn't to vague or bad. I'm new and really wanna understand the code in front of me here that I am screwing up.

Thanks!

AdamKxZ
  • 35
  • 5
  • 1. You want `Console.WriteLine(item.PrintPerson());` - the `PrintPerson` is an instance method, you need an object of class Person to call it. 2. PrintPerson does not print anything, it only returns a string - I suggest to rename it. – Lesiak Aug 27 '20 at 19:38
  • Worked! Thank you very much for the fast response. – AdamKxZ Aug 27 '20 at 19:40

0 Answers0