Hello every one,

What i need to do is to make an array of my own class and then assign values to that array
I made an array and when i try to assign value it gave me an exception

Your support is highly appreciated.

static void Main(string[] args)
        {
            string Fname;
            string Lname;
            string Email;
            int age;
            Person [] Parray = new Person[3];
            Person p1 = new Person();

            for (int i = 0; i < 2; i++)
            {



                Console.WriteLine("Enter your first name ");
               Parray[i].Fname1 =  Console.ReadLine();

                Console.WriteLine("Enter your last name ");
                Parray[i].Lname1= Console.ReadLine();

                //Console.WriteLine("Welcome Mr." + " ");



                //Console.WriteLine("Enter your age ");
                //Parray[i]= int.Parse         (        Console.ReadLine());

            }




        }
    }
}

The person class :-

class Person
    {
        string firstName;
        string lastName;
        int  birthDate;
        string email;

        //public Person(string intifirst, string intilast, int intibirth, string intiemail)
        //{
        //    firstName = intifirst;
        //    lastName = intilast;
        //    birthDate = intibirth;
        //    email = intiemail;
        //}

        //public Person(string intifirst, string intilast, int intibirth)
        //{
        //    firstName = intifirst;
        //    lastName = intilast;
        //    birthDate = intibirth;

        //}

        //public Person(string intifirst, string intilast, string intiemail)
        //{
        //    firstName = intifirst;
        //    lastName = intilast;
        //    email = intiemail;
        //}







          public string Fname1
            {
               get
               {
                   return firstName;
               }
               set
               {
                      firstName = value;
               }
            }


          public string Lname1
          {
              get
              {
                  return lastName;
              }
              set
              {
                  lastName = value;
              }
          }


          public int age 
          {
              get
              {
                  return birthDate;
              }
              set
              {
                  birthDate = value;
              }
          }   




               public void show()
            {
            Console.WriteLine("your first name is " + firstName);
            Console.WriteLine("your last name is " + lastName);
            Console.WriteLine("your E-mail is " + email);
            Console.WriteLine("your age" + birthDate);
        }



    }
}
`

Reworked your program a bit.
If you have trouble with understanding what I did, please ask.

static void Main(string[] args)
        {
            Person[] Parray = new Person[3];
            Person p1 = new Person();
            for (int i = 0; i < Parray.Length; i++)
            {
                Parray[i] = new Person();
                Console.WriteLine("Enter your first name ");
                Parray[i].firstName = Console.ReadLine();
                Console.WriteLine("Enter your last name ");
                Parray[i].lastName = Console.ReadLine();
                Console.WriteLine("Welcome Mr. " + Parray[i].lastName + " ");
                //Console.WriteLine("Enter your age ");
                //Parray[i]= int.Parse         (        Console.ReadLine());
            }
            Console.ReadKey();
        }

        class Person
        {
            public string firstName { get; set; }
            public string lastName { get; set; }
            public int birthDate { get; set; }

            public void show()
            {
                Console.WriteLine("your first name is " + firstName);
                Console.WriteLine("your last name is " + lastName);
                //Console.WriteLine("your E-mail is " + email);
                Console.WriteLine("your age" + birthDate);
            }
        }

ddnabe,

I need to know what this function do ?

 Console.ReadKey()

and this the below line is used instead ofthe property

  public string firstName { get; set; }
  public string lastName { get; set; }
  public int birthDate { get; set; }

Console.ReadKey(); just waits for a key to be pressed, before continuing. Used to keep the console window on screen.
public string firstName { get; set; } is just a syntax shortcut for something you did(which would be equally good), but what if you had to do that a 100 or more times?

//public string firstName { get; set; } is the same as:

// The compiler internally translates the above to something like this:

string X123gHabc; //compiler keeps track of this

public string firstName
        {
           get
           {
               return X123gHabc;
           }
           set
           {
                  X123gHabc = value;
           }
        }

Edited 2 Years Ago by ddanbe: correction

To explain what the original problem was is that while line 7 allocates space to hold references to your class, it doesn't actually create the classes. You can see in ddanbe's code, on his line 7, creates a new Person object and assigns it to the array.

Also, your property 'age' is a poor name. It's not the persons age, it's their birthday. Naming things is very important

I decided to rework it a bit to try and adhere to more modern design principles. I did violate some of these principles because I wanted to limit it to two classes and I didn't want to spend too much time on it :)

You will find that my code is much longer, but that it is more robust and easier to change without breaking everything :) If you have any questions on why things are where they are, just ask.

Program.cs

using System;

namespace TestConsole {
    class Program {
        static private readonly int NumberOfPeople = 3;

        static void Main(string[] args) {
            Person[] people = new Person[NumberOfPeople];

            PopulatePersonArray(people);

            Console.WriteLine();
            Console.WriteLine();

            DisplayPersonArray(people);

            Console.ReadLine();
        }

        static void PopulatePersonArray(Person[] thePeople) {
            for (int i = 0; i < thePeople.Length; i++) {
                thePeople[i] = Person.CreatePerson();
            }
        }

        static void DisplayPersonArray(Person[] thePeople) {
            for (int i = 0; i < thePeople.Length; i++) {
                Console.WriteLine(thePeople[i]);
            }
        }
    }
}

Person.cs

using System;
using System.Globalization;
using System.Text;

namespace TestConsole {
    class Person {
        public String FirstName { get; private set; }
        public String LastName { get; private set; }
        public String EmailAddress { get; private set; }
        public int Age {
            get {
                // This gets is the amount of time from the BirthDay to right now
                TimeSpan span = DateTime.Now - Birthday;

                // By adding the span to the very first day of the calendar, it makes the year 
                // equal to their Age + 1, since the calendar starts on year 1, not year 0.
                // NOTE: It is possible that leap years might cause it to be off if the current
                // day is on or very near your birthday. 
                return (DateTime.MinValue + span).Year - 1;
            }
        }
        public DateTime Birthday { get; private set; }

        static public Person CreatePerson() {
            Person result = new Person();

            result.GatherPersonInformation();

            return result;
        }

        private void GatherPersonInformation() {
            this.FirstName = GetFirstName();
            this.LastName = GetLastName();
            this.EmailAddress = GetEmailAddress();
            this.Birthday = GetBirthday();
        }


        private string GetFirstName() {
            return GetStringInput("What is your first name?");
        }
        private string GetLastName() {
            return GetStringInput("What is your last name?");
        }

        private String GetEmailAddress() {
            return GetStringInput("What is your email address?");
        }

        private DateTime GetBirthday() {
            return GatePastDateInput("What is your birthday (DD/MM/YYYY)?");
        }

        private String GetStringInput(String prompt) {
            String input = String.Empty;

            do {
                Console.Write(prompt);
                input = Console.ReadLine();
                if (String.IsNullOrEmpty(input)) {
                    Console.Write("Please enter a valid value.");
                }
            } while (String.IsNullOrEmpty(input));

            Console.WriteLine();

            return input;
        }

        private DateTime GatePastDateInput(String prompt) {
            String input = String.Empty;
            DateTime output = DateTime.MaxValue;
            Boolean IsGoodDate = false;

            while (IsGoodDate == false) {
                Console.Write(prompt);
                input = Console.ReadLine();
                IsGoodDate = DateTime.TryParseExact(input, "dd/MM/yyyy", CultureInfo.CurrentCulture, DateTimeStyles.None, out output);
                if (IsGoodDate == false || output > DateTime.Now) {
                    Console.WriteLine("Please enter a valid date.");
                    IsGoodDate = false;
                }
            }

            Console.WriteLine();

            return output;
        }
        public override string ToString() {
            StringBuilder output = new StringBuilder();

            output.Append("Your first name is ");
            output.Append(FirstName);
            output.Append(Environment.NewLine);

            output.Append("Your last name is ");
            output.Append(LastName);
            output.Append(Environment.NewLine);

            output.Append("Your E-mail address is ");
            output.Append(EmailAddress);
            output.Append(Environment.NewLine);

            output.Append("Your birthday is ");
            output.Append(Birthday.ToString("dd/MM/yyyy"));
            output.Append(Environment.NewLine);

            output.Append(String.Format("So you are {0} year{1} old.", Age, Age > 1 ? "s" : String.Empty));
            output.Append(Environment.NewLine);
            output.Append(Environment.NewLine);

            return output.ToString();
        }
    }
}

Edited 2 Years Ago by Momerath

Comments
Good job!

Hi, Momerath, long time, no see. :)
At first I wondered why you used static private readonly int NumberOfPeople = 3; I would have used const here. But I googled a bit and came to this.
So, thanks for my memory upgrade on C#!

Yeah, been hanging out on another site after Dani and I couldn't come to an agreement on who owns the code posted here :)

Momerath i have so many questions in your code
so please be paient

What the below functions do

PopulatePersonArray(people);
DisplayPersonArray(people);

Person.CreatePerson();

result.GatherPersonInformation();

(String.IsNullOrEmpty(input

DateTime.MaxValue

output.Append

Why you make separate get function for every member of the class

private void GatherPersonInformation() {
            this.FirstName = GetFirstName();
            this.LastName = GetLastName();
            this.EmailAddress = GetEmailAddress();
            this.Birthday = GetBirthday();
        }

What is the puprose of Timespan

AND thanks very much for ur help and support

To answer your questions in reverse order:

TimeSpan is to calculate how old they are. Since storing someones current Age isn't very robust (what happens when tommorow is their birthday and they use the software again? You'd have to continually ask their age to be accurate). By using the Birthday as our base for Age, we only have to ask them once for it and will know their age forever :)

Methods should strive to do one thing and one thing only. So we have GatherPersonInformation ... well ... gathering the information. It does this by calling methods that get each specific part. If you examine those methods you'll see they call other methods that specialize in one thing (though I didn't seperate out validation from input because I'm lazy :))

As for what the various methods listed do:

PoplulatePersonArray takes an array of Person objects and creates the instance of Person for each element of the array.

DispalyPersonArray takes an array of Person objects and displays them on the console.

Person.CreatePerson creates and instance of a Person object. I didn't use the standard way most people do (Person p = new Person()) as what happens if you have an exception during class construction? Having a method that creates the instance for you allows you to have better error handling.

result.GatherPersonInformation is using an instance of the Person class and 'fills in' the internal values of the instance.

String.IsNullOrEmpty(input) test to see if they actually typed anything in. You can't have a name of "" for example :)

DateTime.MaxValue is the very last day that the calendar can be. DateTime values are structures, so they can't be set to null and it needs to be set to something. It is set to that value so the test later to see if they entered a date before the current Date will fail if the TryParse failed.

output.Append is a call to the StringBuilder method (output is an instance of StringBuilder) to add something to the end of the string. In general, concatinating strings in C# is bad. Because string are immutable, every time you concatinate a string it has to create a whole new object. Do lots of concatination and memory will be filled with strings :) StringBuilder allows you to do concatination without the overhead of having to create new strings.

------

Your original problem could be stated as:
Get the information about some people.
Display the information about some people.

So we create methods that do exactly that. We then break down each of those methods into what they need to do like we did in GatherPersonInformation (we need to get a first name, get a last name, get an email address and get a birthday).

Why do this? Well, in your original code, what if the problem was changed to 'get the information from a database'. You'd have to make all the changes and retest everything. In mine, you'd just need to change the GatherPersonInformation method and test it. This means less chance you'll screw up other code :)

This question has already been answered. Start a new discussion instead.