Displaying a person's personal information with formatting












5














I am learning C# from a book, and there is an exercise as follows:




Write a program that has a person enter full name, age, and phone
number. Display this information with formatting. Also display the
person's initials.




I wrote some code and I feel that it could be improved, so I ask anyone to comment on it.



using System;
using System.Collections.Generic;

internal class Person
{
public string fname;
public string mname;
public string lname;
public int age;
public string phnumber;

public Person()
{
fname = KeyInput.keyIn("nnPlease enter your first name");
if (fname.ToLower() == "exit") return;

mname = KeyInput.keyIn("nPlease enter your middle name");
lname = KeyInput.keyIn("nPlease enter your last name");

while (true)
{
try
{
age = Convert.ToInt32(KeyInput.keyIn("nPlease enter your age"));
break;
}

catch (ArgumentException)
{
Console.WriteLine("No value was entered");
}

catch (FormatException)
{
Console.WriteLine("You didn't entered a valid number");
}

catch (Exception e)
{
Console.WriteLine("Something went wrong with the conversion.");
}
}

phnumber = KeyInput.keyIn("nPlease enter your phone number");
}

public void personDataDisplay()
{
Console.WriteLine("nYour name is: " + fname + " " + mname[0] + "." + " " + lname);
Console.WriteLine("Your initials are: " + fname[0] + mname[0] + lname[0]);
Console.WriteLine("Your age is: " + age);
Console.WriteLine("Your phone number is: " + phnumber + "n");
}
}

internal class KeyInput
{
public static string keyIn(string scrtext)
{
Console.WriteLine(scrtext);
string buffer = Console.ReadLine();
return buffer;
}
}

internal class MyApp
{
public static void Main()
{
Console.WriteLine("Please enter data for person(s). Enter EXIT to end.");

List<Person> list_persons = new List<Person>();

while (true)
{
Person person = new Person();
list_persons.Add(person);

if (person.fname.ToLower() == "exit")
break;
}

foreach (Person person in list_persons)
{
if (person.fname.ToLower() == "exit")
break;

person.personDataDisplay();
}
}
}









share|improve this question





























    5














    I am learning C# from a book, and there is an exercise as follows:




    Write a program that has a person enter full name, age, and phone
    number. Display this information with formatting. Also display the
    person's initials.




    I wrote some code and I feel that it could be improved, so I ask anyone to comment on it.



    using System;
    using System.Collections.Generic;

    internal class Person
    {
    public string fname;
    public string mname;
    public string lname;
    public int age;
    public string phnumber;

    public Person()
    {
    fname = KeyInput.keyIn("nnPlease enter your first name");
    if (fname.ToLower() == "exit") return;

    mname = KeyInput.keyIn("nPlease enter your middle name");
    lname = KeyInput.keyIn("nPlease enter your last name");

    while (true)
    {
    try
    {
    age = Convert.ToInt32(KeyInput.keyIn("nPlease enter your age"));
    break;
    }

    catch (ArgumentException)
    {
    Console.WriteLine("No value was entered");
    }

    catch (FormatException)
    {
    Console.WriteLine("You didn't entered a valid number");
    }

    catch (Exception e)
    {
    Console.WriteLine("Something went wrong with the conversion.");
    }
    }

    phnumber = KeyInput.keyIn("nPlease enter your phone number");
    }

    public void personDataDisplay()
    {
    Console.WriteLine("nYour name is: " + fname + " " + mname[0] + "." + " " + lname);
    Console.WriteLine("Your initials are: " + fname[0] + mname[0] + lname[0]);
    Console.WriteLine("Your age is: " + age);
    Console.WriteLine("Your phone number is: " + phnumber + "n");
    }
    }

    internal class KeyInput
    {
    public static string keyIn(string scrtext)
    {
    Console.WriteLine(scrtext);
    string buffer = Console.ReadLine();
    return buffer;
    }
    }

    internal class MyApp
    {
    public static void Main()
    {
    Console.WriteLine("Please enter data for person(s). Enter EXIT to end.");

    List<Person> list_persons = new List<Person>();

    while (true)
    {
    Person person = new Person();
    list_persons.Add(person);

    if (person.fname.ToLower() == "exit")
    break;
    }

    foreach (Person person in list_persons)
    {
    if (person.fname.ToLower() == "exit")
    break;

    person.personDataDisplay();
    }
    }
    }









    share|improve this question



























      5












      5








      5







      I am learning C# from a book, and there is an exercise as follows:




      Write a program that has a person enter full name, age, and phone
      number. Display this information with formatting. Also display the
      person's initials.




      I wrote some code and I feel that it could be improved, so I ask anyone to comment on it.



      using System;
      using System.Collections.Generic;

      internal class Person
      {
      public string fname;
      public string mname;
      public string lname;
      public int age;
      public string phnumber;

      public Person()
      {
      fname = KeyInput.keyIn("nnPlease enter your first name");
      if (fname.ToLower() == "exit") return;

      mname = KeyInput.keyIn("nPlease enter your middle name");
      lname = KeyInput.keyIn("nPlease enter your last name");

      while (true)
      {
      try
      {
      age = Convert.ToInt32(KeyInput.keyIn("nPlease enter your age"));
      break;
      }

      catch (ArgumentException)
      {
      Console.WriteLine("No value was entered");
      }

      catch (FormatException)
      {
      Console.WriteLine("You didn't entered a valid number");
      }

      catch (Exception e)
      {
      Console.WriteLine("Something went wrong with the conversion.");
      }
      }

      phnumber = KeyInput.keyIn("nPlease enter your phone number");
      }

      public void personDataDisplay()
      {
      Console.WriteLine("nYour name is: " + fname + " " + mname[0] + "." + " " + lname);
      Console.WriteLine("Your initials are: " + fname[0] + mname[0] + lname[0]);
      Console.WriteLine("Your age is: " + age);
      Console.WriteLine("Your phone number is: " + phnumber + "n");
      }
      }

      internal class KeyInput
      {
      public static string keyIn(string scrtext)
      {
      Console.WriteLine(scrtext);
      string buffer = Console.ReadLine();
      return buffer;
      }
      }

      internal class MyApp
      {
      public static void Main()
      {
      Console.WriteLine("Please enter data for person(s). Enter EXIT to end.");

      List<Person> list_persons = new List<Person>();

      while (true)
      {
      Person person = new Person();
      list_persons.Add(person);

      if (person.fname.ToLower() == "exit")
      break;
      }

      foreach (Person person in list_persons)
      {
      if (person.fname.ToLower() == "exit")
      break;

      person.personDataDisplay();
      }
      }
      }









      share|improve this question















      I am learning C# from a book, and there is an exercise as follows:




      Write a program that has a person enter full name, age, and phone
      number. Display this information with formatting. Also display the
      person's initials.




      I wrote some code and I feel that it could be improved, so I ask anyone to comment on it.



      using System;
      using System.Collections.Generic;

      internal class Person
      {
      public string fname;
      public string mname;
      public string lname;
      public int age;
      public string phnumber;

      public Person()
      {
      fname = KeyInput.keyIn("nnPlease enter your first name");
      if (fname.ToLower() == "exit") return;

      mname = KeyInput.keyIn("nPlease enter your middle name");
      lname = KeyInput.keyIn("nPlease enter your last name");

      while (true)
      {
      try
      {
      age = Convert.ToInt32(KeyInput.keyIn("nPlease enter your age"));
      break;
      }

      catch (ArgumentException)
      {
      Console.WriteLine("No value was entered");
      }

      catch (FormatException)
      {
      Console.WriteLine("You didn't entered a valid number");
      }

      catch (Exception e)
      {
      Console.WriteLine("Something went wrong with the conversion.");
      }
      }

      phnumber = KeyInput.keyIn("nPlease enter your phone number");
      }

      public void personDataDisplay()
      {
      Console.WriteLine("nYour name is: " + fname + " " + mname[0] + "." + " " + lname);
      Console.WriteLine("Your initials are: " + fname[0] + mname[0] + lname[0]);
      Console.WriteLine("Your age is: " + age);
      Console.WriteLine("Your phone number is: " + phnumber + "n");
      }
      }

      internal class KeyInput
      {
      public static string keyIn(string scrtext)
      {
      Console.WriteLine(scrtext);
      string buffer = Console.ReadLine();
      return buffer;
      }
      }

      internal class MyApp
      {
      public static void Main()
      {
      Console.WriteLine("Please enter data for person(s). Enter EXIT to end.");

      List<Person> list_persons = new List<Person>();

      while (true)
      {
      Person person = new Person();
      list_persons.Add(person);

      if (person.fname.ToLower() == "exit")
      break;
      }

      foreach (Person person in list_persons)
      {
      if (person.fname.ToLower() == "exit")
      break;

      person.personDataDisplay();
      }
      }
      }






      c# console formatting






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 27 '14 at 7:19









      Jamal

      30.3k11116226




      30.3k11116226










      asked Mar 13 '13 at 11:51









      Nenad Bulatovic

      2442514




      2442514






















          5 Answers
          5






          active

          oldest

          votes


















          11














          In designing classes we should try and confirm to the Single Responsibility Principle. Each class should only do one thing. Sometimes defining what makes a single responsibility is hard, but your Person class clearly does two things: it represents a person, and it questions the user via the console. This makes it difficult to reuse your Person class: what if you wanted to create a Person from a database, or a file or a web request? You would be better splitting this into a PersonQuestionnaire class which is responsible for creating a Person from a console input.



          You should never have any significant logic in your constructor like you have here. Design your constructors to simply save any parameters and set up any default values. Any logic involving external classes, such as the Console, should definitely be placed in another method that is called once the object is constructed.



          You should consider using the int.TryParse() method to read the age. Catching exceptions is slow (you will notice you ever write applications that are doing a lot of this type of thing), verbose, and sometimes unpredictable. You should definitely avoid catching the top level Exception type other than where you can do something meaningful: doing a lot of this will make your applications very difficult to debug.






          share|improve this answer





























            11














            In addition to the other good advice in the other answers, I would add:




            • Do not catch any exception that you could have prevented. Instead, prevent the exception.


            There is never any reason to catch ArgumentException because it should never be thrown in the first place. You are responsible for ensuring that when you pass arguments to a method, that those arguments meet the requirements of the method you're calling. You know if the string you're going to pass is null or empty; if it is, don't pass it.



            Read this for more information:



            http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx






            share|improve this answer





























              5














              What happens when someone does not have a middle name? I think you'll find that if you test that, nothing good happens.






              share|improve this answer





















              • You are right, I should better check if it is null or empty, however this is misunderstanding due to language/region barrier, as in my country everyone has a middle name as it is considered to be one of parents name (usually father's name).
                – Nenad Bulatovic
                Mar 13 '13 at 18:37






              • 1




                @nenad: I would hazard a guess that most of the people in your country have a middle name, not everyone. One of the things you learn writing software to be used by people is that assuming that what most people do is the same as what everyone does just leads to pain later.
                – Eric Lippert
                Mar 13 '13 at 21:00



















              2














              Person



              Split user-input from your class definition. It's not a good practice to mix the input in the definition. Try to decouple as much as possible. I also redefined the properties in the class:



              public string FirstName { get; set; }
              public string MiddleName { get; set; }
              public string LastName { get; set; }
              public int Age { get; set; }
              public string Phone { get; set; }


              Same goes for displaying the information about the person. It's not a good practice to write it to screen from within this class. Just override the ToString()-method and display this on screen. The FirstChar()-method is there to check if the name exists to take the first character of that name, otherwise return a spacer.



              public override string ToString()
              {
              StringBuilder sb = new StringBuilder();
              sb.AppendLine(String.Format("Your name is: {0} {1}. {2}", FirstName, FirstChar(MiddleName), LastName));
              sb.AppendLine(String.Format("Your initials are: {0}{1}{2}", FirstChar(FirstName), FirstChar(MiddleName), FirstChar(LastName)));
              sb.AppendLine(String.Format("Your age is: {0}", Age));
              sb.AppendLine(String.Format("Your phone number is: {0}", Phone));

              return sb.ToString();
              }

              private char FirstChar(string input)
              {
              return String.IsNullOrEmpty(input) ? ' ' : input[0];
              }


              Input



              Since the input is not mixed in the Person-class we have to declare it somewhere else. In this example I put the input-code in the KeyInput class. The method returns an instance of the Person-class and if the user enters "exit", null is returned. This way we can later on catch if the user wants to stop.



              public static Person NewPerson()
              {
              string first = KeyInput.keyIn("Please enter your first name: ");
              if (first.ToLower().Equals("exit"))
              return null;

              string middle = KeyInput.keyIn("Please enter your middle name: ");
              string last = KeyInput.keyIn("Please enter your last name: ");
              int age = 0;

              while (true)
              {
              try
              {
              age = Convert.ToInt32(KeyInput.keyIn("Please enter your age"));
              break;
              }
              catch (ArgumentException)
              {
              Console.WriteLine("No value was entered");
              }
              catch (FormatException)
              {
              Console.WriteLine("You didn't entered a valid number");
              }
              catch (Exception)
              {
              Console.WriteLine("Something went wrong with the conversion.");
              }
              }

              string phone = KeyInput.keyIn("Please enter your phone numbern");

              return new Person { FirstName = first, MiddleName = middle, LastName = last, Age = age, Phone = phone };
              }


              Main



              Since all previous code has changed, the logic of your Main will change too.



              public static void Main()
              {
              Console.WriteLine("Please enter data for person(s). Enter EXIT to end.");

              List<Person> people = new List<Person>();

              while (true)
              {
              var person = KeyInput.NewPerson();

              if(person == null)
              break;

              people.Add(person);
              }

              foreach (var person in people)
              {
              Console.WriteLine(person.ToString());
              }
              }


              Summary



              I'm not saying that my code is perfect in any way. Probably my code could be revised and corrected as well. I only want to show you the way how you decouple user-input from class-definitions, use proper variable names, bring a proper structure and logic in your code. Please feel free if to comment if anything's wrong with my code.



              Edit:



              Thanks to the valid comments I received, I edited the code. The posters of the comments were absolutely right. I've also rewritten the Initial()-method to a more correct logic. Here's the result in it's entirety:



              internal class Person
              {
              public string FirstName { get; set; }
              public string MiddleName { get; set; }
              public string LastName { get; set; }
              public int Age { get; set; }
              public string Phone { get; set; }

              public override string ToString()
              {
              var sb = new StringBuilder();

              sb.AppendFormat("Your name is: {0} {1} {2}", FirstName, Initial(MiddleName, true), LastName).AppendLine();
              sb.AppendFormat("Your initials are: {0}{1}{2}", Initial(FirstName, false), Initial(MiddleName, false), Initial(LastName, false)).AppendLine();
              sb.AppendFormat("Your age is: {0}", Age).AppendLine();
              sb.AppendFormat("Your phone number is: {0}", Phone).AppendLine();

              return sb.ToString();
              }

              private static string Initial(string input, bool dot)
              {
              if (String.IsNullOrEmpty(input))
              return input;

              if(input.Contains(" "))
              return input.Split(' ').Aggregate("", (current, s) => current + s[0]);

              return input[0] + (dot ? "." : "");
              }
              }

              internal class KeyInput
              {
              public static string KeyIn(string scrtext)
              {
              Console.Write(scrtext);
              var buffer = Console.ReadLine();
              return buffer;
              }
              }

              internal class Program
              {
              public static void Main(string args)
              {
              Console.WriteLine("Please enter data for one or more person(s)." + Environment.NewLine);

              var people = new List<Person>();
              var newInput = true;

              while (newInput)
              {
              var person = GetNewPerson();
              people.Add(person);
              newInput = KeyInput.KeyIn("Add another person? (Y/N): ").ToLower().Equals("y");
              }

              foreach (var person in people)
              Console.WriteLine(person.ToString() + Environment.NewLine);

              Console.ReadKey();
              }

              public static Person GetNewPerson()
              {
              var first = KeyInput.KeyIn("Please enter your first name: ");
              var middle = KeyInput.KeyIn("Please enter your middle name: ");
              var last = KeyInput.KeyIn("Please enter your last name: ");
              int age;

              while (!int.TryParse(KeyInput.KeyIn("Please enter your age: "), out age))
              Console.WriteLine("Invalid input, try again...");

              var phone = KeyInput.KeyIn("Please enter your phone number: ");

              return new Person { FirstName = first, MiddleName = middle, LastName = last, Age = age, Phone = phone };
              }
              }


              Still feel free to comment, I'm learning myself! ;)






              share|improve this answer



















              • 4




                NewPerson() feels wrong in the KeyInput class. They are two completely separate operations.
                – Jeff Vanzella
                Mar 13 '13 at 15:55






              • 2




                I don't like seeing while(true) - it makes me have to figure out why you're looping - I'd change it to while(!int.TryParse(KeyInput.keyIn("Please enter your age"), out age)) or use a well named variable. I'd also use sb.AppendFormat(...).AppendLine() but that's personal preference.
                – RobH
                Mar 13 '13 at 16:02












              • I edited my answer based on your useful comments :)
                – Abbas
                Mar 13 '13 at 22:46












              • Thank you for your effort to provide such a detailed insight into my code.
                – Nenad Bulatovic
                Mar 14 '13 at 9:41










              • No problem, I hope it helped you further!
                – Abbas
                Mar 14 '13 at 10:27



















              -2














              I have a question?



              In my project I wanted to generate a ID automatically by students first name character last name character and his birthday combination of this I want to generate I'd help please






              share|improve this answer








              New contributor




              Faizshaikh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.


















                Your Answer





                StackExchange.ifUsing("editor", function () {
                return StackExchange.using("mathjaxEditing", function () {
                StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
                StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
                });
                });
                }, "mathjax-editing");

                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "196"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: false,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: null,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f23835%2fdisplaying-a-persons-personal-information-with-formatting%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                5 Answers
                5






                active

                oldest

                votes








                5 Answers
                5






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                11














                In designing classes we should try and confirm to the Single Responsibility Principle. Each class should only do one thing. Sometimes defining what makes a single responsibility is hard, but your Person class clearly does two things: it represents a person, and it questions the user via the console. This makes it difficult to reuse your Person class: what if you wanted to create a Person from a database, or a file or a web request? You would be better splitting this into a PersonQuestionnaire class which is responsible for creating a Person from a console input.



                You should never have any significant logic in your constructor like you have here. Design your constructors to simply save any parameters and set up any default values. Any logic involving external classes, such as the Console, should definitely be placed in another method that is called once the object is constructed.



                You should consider using the int.TryParse() method to read the age. Catching exceptions is slow (you will notice you ever write applications that are doing a lot of this type of thing), verbose, and sometimes unpredictable. You should definitely avoid catching the top level Exception type other than where you can do something meaningful: doing a lot of this will make your applications very difficult to debug.






                share|improve this answer


























                  11














                  In designing classes we should try and confirm to the Single Responsibility Principle. Each class should only do one thing. Sometimes defining what makes a single responsibility is hard, but your Person class clearly does two things: it represents a person, and it questions the user via the console. This makes it difficult to reuse your Person class: what if you wanted to create a Person from a database, or a file or a web request? You would be better splitting this into a PersonQuestionnaire class which is responsible for creating a Person from a console input.



                  You should never have any significant logic in your constructor like you have here. Design your constructors to simply save any parameters and set up any default values. Any logic involving external classes, such as the Console, should definitely be placed in another method that is called once the object is constructed.



                  You should consider using the int.TryParse() method to read the age. Catching exceptions is slow (you will notice you ever write applications that are doing a lot of this type of thing), verbose, and sometimes unpredictable. You should definitely avoid catching the top level Exception type other than where you can do something meaningful: doing a lot of this will make your applications very difficult to debug.






                  share|improve this answer
























                    11












                    11








                    11






                    In designing classes we should try and confirm to the Single Responsibility Principle. Each class should only do one thing. Sometimes defining what makes a single responsibility is hard, but your Person class clearly does two things: it represents a person, and it questions the user via the console. This makes it difficult to reuse your Person class: what if you wanted to create a Person from a database, or a file or a web request? You would be better splitting this into a PersonQuestionnaire class which is responsible for creating a Person from a console input.



                    You should never have any significant logic in your constructor like you have here. Design your constructors to simply save any parameters and set up any default values. Any logic involving external classes, such as the Console, should definitely be placed in another method that is called once the object is constructed.



                    You should consider using the int.TryParse() method to read the age. Catching exceptions is slow (you will notice you ever write applications that are doing a lot of this type of thing), verbose, and sometimes unpredictable. You should definitely avoid catching the top level Exception type other than where you can do something meaningful: doing a lot of this will make your applications very difficult to debug.






                    share|improve this answer












                    In designing classes we should try and confirm to the Single Responsibility Principle. Each class should only do one thing. Sometimes defining what makes a single responsibility is hard, but your Person class clearly does two things: it represents a person, and it questions the user via the console. This makes it difficult to reuse your Person class: what if you wanted to create a Person from a database, or a file or a web request? You would be better splitting this into a PersonQuestionnaire class which is responsible for creating a Person from a console input.



                    You should never have any significant logic in your constructor like you have here. Design your constructors to simply save any parameters and set up any default values. Any logic involving external classes, such as the Console, should definitely be placed in another method that is called once the object is constructed.



                    You should consider using the int.TryParse() method to read the age. Catching exceptions is slow (you will notice you ever write applications that are doing a lot of this type of thing), verbose, and sometimes unpredictable. You should definitely avoid catching the top level Exception type other than where you can do something meaningful: doing a lot of this will make your applications very difficult to debug.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 13 '13 at 12:33









                    Tim Rogers

                    22623




                    22623

























                        11














                        In addition to the other good advice in the other answers, I would add:




                        • Do not catch any exception that you could have prevented. Instead, prevent the exception.


                        There is never any reason to catch ArgumentException because it should never be thrown in the first place. You are responsible for ensuring that when you pass arguments to a method, that those arguments meet the requirements of the method you're calling. You know if the string you're going to pass is null or empty; if it is, don't pass it.



                        Read this for more information:



                        http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx






                        share|improve this answer


























                          11














                          In addition to the other good advice in the other answers, I would add:




                          • Do not catch any exception that you could have prevented. Instead, prevent the exception.


                          There is never any reason to catch ArgumentException because it should never be thrown in the first place. You are responsible for ensuring that when you pass arguments to a method, that those arguments meet the requirements of the method you're calling. You know if the string you're going to pass is null or empty; if it is, don't pass it.



                          Read this for more information:



                          http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx






                          share|improve this answer
























                            11












                            11








                            11






                            In addition to the other good advice in the other answers, I would add:




                            • Do not catch any exception that you could have prevented. Instead, prevent the exception.


                            There is never any reason to catch ArgumentException because it should never be thrown in the first place. You are responsible for ensuring that when you pass arguments to a method, that those arguments meet the requirements of the method you're calling. You know if the string you're going to pass is null or empty; if it is, don't pass it.



                            Read this for more information:



                            http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx






                            share|improve this answer












                            In addition to the other good advice in the other answers, I would add:




                            • Do not catch any exception that you could have prevented. Instead, prevent the exception.


                            There is never any reason to catch ArgumentException because it should never be thrown in the first place. You are responsible for ensuring that when you pass arguments to a method, that those arguments meet the requirements of the method you're calling. You know if the string you're going to pass is null or empty; if it is, don't pass it.



                            Read this for more information:



                            http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 13 '13 at 15:39









                            Eric Lippert

                            12.7k42746




                            12.7k42746























                                5














                                What happens when someone does not have a middle name? I think you'll find that if you test that, nothing good happens.






                                share|improve this answer





















                                • You are right, I should better check if it is null or empty, however this is misunderstanding due to language/region barrier, as in my country everyone has a middle name as it is considered to be one of parents name (usually father's name).
                                  – Nenad Bulatovic
                                  Mar 13 '13 at 18:37






                                • 1




                                  @nenad: I would hazard a guess that most of the people in your country have a middle name, not everyone. One of the things you learn writing software to be used by people is that assuming that what most people do is the same as what everyone does just leads to pain later.
                                  – Eric Lippert
                                  Mar 13 '13 at 21:00
















                                5














                                What happens when someone does not have a middle name? I think you'll find that if you test that, nothing good happens.






                                share|improve this answer





















                                • You are right, I should better check if it is null or empty, however this is misunderstanding due to language/region barrier, as in my country everyone has a middle name as it is considered to be one of parents name (usually father's name).
                                  – Nenad Bulatovic
                                  Mar 13 '13 at 18:37






                                • 1




                                  @nenad: I would hazard a guess that most of the people in your country have a middle name, not everyone. One of the things you learn writing software to be used by people is that assuming that what most people do is the same as what everyone does just leads to pain later.
                                  – Eric Lippert
                                  Mar 13 '13 at 21:00














                                5












                                5








                                5






                                What happens when someone does not have a middle name? I think you'll find that if you test that, nothing good happens.






                                share|improve this answer












                                What happens when someone does not have a middle name? I think you'll find that if you test that, nothing good happens.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Mar 13 '13 at 15:41









                                Eric Lippert

                                12.7k42746




                                12.7k42746












                                • You are right, I should better check if it is null or empty, however this is misunderstanding due to language/region barrier, as in my country everyone has a middle name as it is considered to be one of parents name (usually father's name).
                                  – Nenad Bulatovic
                                  Mar 13 '13 at 18:37






                                • 1




                                  @nenad: I would hazard a guess that most of the people in your country have a middle name, not everyone. One of the things you learn writing software to be used by people is that assuming that what most people do is the same as what everyone does just leads to pain later.
                                  – Eric Lippert
                                  Mar 13 '13 at 21:00


















                                • You are right, I should better check if it is null or empty, however this is misunderstanding due to language/region barrier, as in my country everyone has a middle name as it is considered to be one of parents name (usually father's name).
                                  – Nenad Bulatovic
                                  Mar 13 '13 at 18:37






                                • 1




                                  @nenad: I would hazard a guess that most of the people in your country have a middle name, not everyone. One of the things you learn writing software to be used by people is that assuming that what most people do is the same as what everyone does just leads to pain later.
                                  – Eric Lippert
                                  Mar 13 '13 at 21:00
















                                You are right, I should better check if it is null or empty, however this is misunderstanding due to language/region barrier, as in my country everyone has a middle name as it is considered to be one of parents name (usually father's name).
                                – Nenad Bulatovic
                                Mar 13 '13 at 18:37




                                You are right, I should better check if it is null or empty, however this is misunderstanding due to language/region barrier, as in my country everyone has a middle name as it is considered to be one of parents name (usually father's name).
                                – Nenad Bulatovic
                                Mar 13 '13 at 18:37




                                1




                                1




                                @nenad: I would hazard a guess that most of the people in your country have a middle name, not everyone. One of the things you learn writing software to be used by people is that assuming that what most people do is the same as what everyone does just leads to pain later.
                                – Eric Lippert
                                Mar 13 '13 at 21:00




                                @nenad: I would hazard a guess that most of the people in your country have a middle name, not everyone. One of the things you learn writing software to be used by people is that assuming that what most people do is the same as what everyone does just leads to pain later.
                                – Eric Lippert
                                Mar 13 '13 at 21:00











                                2














                                Person



                                Split user-input from your class definition. It's not a good practice to mix the input in the definition. Try to decouple as much as possible. I also redefined the properties in the class:



                                public string FirstName { get; set; }
                                public string MiddleName { get; set; }
                                public string LastName { get; set; }
                                public int Age { get; set; }
                                public string Phone { get; set; }


                                Same goes for displaying the information about the person. It's not a good practice to write it to screen from within this class. Just override the ToString()-method and display this on screen. The FirstChar()-method is there to check if the name exists to take the first character of that name, otherwise return a spacer.



                                public override string ToString()
                                {
                                StringBuilder sb = new StringBuilder();
                                sb.AppendLine(String.Format("Your name is: {0} {1}. {2}", FirstName, FirstChar(MiddleName), LastName));
                                sb.AppendLine(String.Format("Your initials are: {0}{1}{2}", FirstChar(FirstName), FirstChar(MiddleName), FirstChar(LastName)));
                                sb.AppendLine(String.Format("Your age is: {0}", Age));
                                sb.AppendLine(String.Format("Your phone number is: {0}", Phone));

                                return sb.ToString();
                                }

                                private char FirstChar(string input)
                                {
                                return String.IsNullOrEmpty(input) ? ' ' : input[0];
                                }


                                Input



                                Since the input is not mixed in the Person-class we have to declare it somewhere else. In this example I put the input-code in the KeyInput class. The method returns an instance of the Person-class and if the user enters "exit", null is returned. This way we can later on catch if the user wants to stop.



                                public static Person NewPerson()
                                {
                                string first = KeyInput.keyIn("Please enter your first name: ");
                                if (first.ToLower().Equals("exit"))
                                return null;

                                string middle = KeyInput.keyIn("Please enter your middle name: ");
                                string last = KeyInput.keyIn("Please enter your last name: ");
                                int age = 0;

                                while (true)
                                {
                                try
                                {
                                age = Convert.ToInt32(KeyInput.keyIn("Please enter your age"));
                                break;
                                }
                                catch (ArgumentException)
                                {
                                Console.WriteLine("No value was entered");
                                }
                                catch (FormatException)
                                {
                                Console.WriteLine("You didn't entered a valid number");
                                }
                                catch (Exception)
                                {
                                Console.WriteLine("Something went wrong with the conversion.");
                                }
                                }

                                string phone = KeyInput.keyIn("Please enter your phone numbern");

                                return new Person { FirstName = first, MiddleName = middle, LastName = last, Age = age, Phone = phone };
                                }


                                Main



                                Since all previous code has changed, the logic of your Main will change too.



                                public static void Main()
                                {
                                Console.WriteLine("Please enter data for person(s). Enter EXIT to end.");

                                List<Person> people = new List<Person>();

                                while (true)
                                {
                                var person = KeyInput.NewPerson();

                                if(person == null)
                                break;

                                people.Add(person);
                                }

                                foreach (var person in people)
                                {
                                Console.WriteLine(person.ToString());
                                }
                                }


                                Summary



                                I'm not saying that my code is perfect in any way. Probably my code could be revised and corrected as well. I only want to show you the way how you decouple user-input from class-definitions, use proper variable names, bring a proper structure and logic in your code. Please feel free if to comment if anything's wrong with my code.



                                Edit:



                                Thanks to the valid comments I received, I edited the code. The posters of the comments were absolutely right. I've also rewritten the Initial()-method to a more correct logic. Here's the result in it's entirety:



                                internal class Person
                                {
                                public string FirstName { get; set; }
                                public string MiddleName { get; set; }
                                public string LastName { get; set; }
                                public int Age { get; set; }
                                public string Phone { get; set; }

                                public override string ToString()
                                {
                                var sb = new StringBuilder();

                                sb.AppendFormat("Your name is: {0} {1} {2}", FirstName, Initial(MiddleName, true), LastName).AppendLine();
                                sb.AppendFormat("Your initials are: {0}{1}{2}", Initial(FirstName, false), Initial(MiddleName, false), Initial(LastName, false)).AppendLine();
                                sb.AppendFormat("Your age is: {0}", Age).AppendLine();
                                sb.AppendFormat("Your phone number is: {0}", Phone).AppendLine();

                                return sb.ToString();
                                }

                                private static string Initial(string input, bool dot)
                                {
                                if (String.IsNullOrEmpty(input))
                                return input;

                                if(input.Contains(" "))
                                return input.Split(' ').Aggregate("", (current, s) => current + s[0]);

                                return input[0] + (dot ? "." : "");
                                }
                                }

                                internal class KeyInput
                                {
                                public static string KeyIn(string scrtext)
                                {
                                Console.Write(scrtext);
                                var buffer = Console.ReadLine();
                                return buffer;
                                }
                                }

                                internal class Program
                                {
                                public static void Main(string args)
                                {
                                Console.WriteLine("Please enter data for one or more person(s)." + Environment.NewLine);

                                var people = new List<Person>();
                                var newInput = true;

                                while (newInput)
                                {
                                var person = GetNewPerson();
                                people.Add(person);
                                newInput = KeyInput.KeyIn("Add another person? (Y/N): ").ToLower().Equals("y");
                                }

                                foreach (var person in people)
                                Console.WriteLine(person.ToString() + Environment.NewLine);

                                Console.ReadKey();
                                }

                                public static Person GetNewPerson()
                                {
                                var first = KeyInput.KeyIn("Please enter your first name: ");
                                var middle = KeyInput.KeyIn("Please enter your middle name: ");
                                var last = KeyInput.KeyIn("Please enter your last name: ");
                                int age;

                                while (!int.TryParse(KeyInput.KeyIn("Please enter your age: "), out age))
                                Console.WriteLine("Invalid input, try again...");

                                var phone = KeyInput.KeyIn("Please enter your phone number: ");

                                return new Person { FirstName = first, MiddleName = middle, LastName = last, Age = age, Phone = phone };
                                }
                                }


                                Still feel free to comment, I'm learning myself! ;)






                                share|improve this answer



















                                • 4




                                  NewPerson() feels wrong in the KeyInput class. They are two completely separate operations.
                                  – Jeff Vanzella
                                  Mar 13 '13 at 15:55






                                • 2




                                  I don't like seeing while(true) - it makes me have to figure out why you're looping - I'd change it to while(!int.TryParse(KeyInput.keyIn("Please enter your age"), out age)) or use a well named variable. I'd also use sb.AppendFormat(...).AppendLine() but that's personal preference.
                                  – RobH
                                  Mar 13 '13 at 16:02












                                • I edited my answer based on your useful comments :)
                                  – Abbas
                                  Mar 13 '13 at 22:46












                                • Thank you for your effort to provide such a detailed insight into my code.
                                  – Nenad Bulatovic
                                  Mar 14 '13 at 9:41










                                • No problem, I hope it helped you further!
                                  – Abbas
                                  Mar 14 '13 at 10:27
















                                2














                                Person



                                Split user-input from your class definition. It's not a good practice to mix the input in the definition. Try to decouple as much as possible. I also redefined the properties in the class:



                                public string FirstName { get; set; }
                                public string MiddleName { get; set; }
                                public string LastName { get; set; }
                                public int Age { get; set; }
                                public string Phone { get; set; }


                                Same goes for displaying the information about the person. It's not a good practice to write it to screen from within this class. Just override the ToString()-method and display this on screen. The FirstChar()-method is there to check if the name exists to take the first character of that name, otherwise return a spacer.



                                public override string ToString()
                                {
                                StringBuilder sb = new StringBuilder();
                                sb.AppendLine(String.Format("Your name is: {0} {1}. {2}", FirstName, FirstChar(MiddleName), LastName));
                                sb.AppendLine(String.Format("Your initials are: {0}{1}{2}", FirstChar(FirstName), FirstChar(MiddleName), FirstChar(LastName)));
                                sb.AppendLine(String.Format("Your age is: {0}", Age));
                                sb.AppendLine(String.Format("Your phone number is: {0}", Phone));

                                return sb.ToString();
                                }

                                private char FirstChar(string input)
                                {
                                return String.IsNullOrEmpty(input) ? ' ' : input[0];
                                }


                                Input



                                Since the input is not mixed in the Person-class we have to declare it somewhere else. In this example I put the input-code in the KeyInput class. The method returns an instance of the Person-class and if the user enters "exit", null is returned. This way we can later on catch if the user wants to stop.



                                public static Person NewPerson()
                                {
                                string first = KeyInput.keyIn("Please enter your first name: ");
                                if (first.ToLower().Equals("exit"))
                                return null;

                                string middle = KeyInput.keyIn("Please enter your middle name: ");
                                string last = KeyInput.keyIn("Please enter your last name: ");
                                int age = 0;

                                while (true)
                                {
                                try
                                {
                                age = Convert.ToInt32(KeyInput.keyIn("Please enter your age"));
                                break;
                                }
                                catch (ArgumentException)
                                {
                                Console.WriteLine("No value was entered");
                                }
                                catch (FormatException)
                                {
                                Console.WriteLine("You didn't entered a valid number");
                                }
                                catch (Exception)
                                {
                                Console.WriteLine("Something went wrong with the conversion.");
                                }
                                }

                                string phone = KeyInput.keyIn("Please enter your phone numbern");

                                return new Person { FirstName = first, MiddleName = middle, LastName = last, Age = age, Phone = phone };
                                }


                                Main



                                Since all previous code has changed, the logic of your Main will change too.



                                public static void Main()
                                {
                                Console.WriteLine("Please enter data for person(s). Enter EXIT to end.");

                                List<Person> people = new List<Person>();

                                while (true)
                                {
                                var person = KeyInput.NewPerson();

                                if(person == null)
                                break;

                                people.Add(person);
                                }

                                foreach (var person in people)
                                {
                                Console.WriteLine(person.ToString());
                                }
                                }


                                Summary



                                I'm not saying that my code is perfect in any way. Probably my code could be revised and corrected as well. I only want to show you the way how you decouple user-input from class-definitions, use proper variable names, bring a proper structure and logic in your code. Please feel free if to comment if anything's wrong with my code.



                                Edit:



                                Thanks to the valid comments I received, I edited the code. The posters of the comments were absolutely right. I've also rewritten the Initial()-method to a more correct logic. Here's the result in it's entirety:



                                internal class Person
                                {
                                public string FirstName { get; set; }
                                public string MiddleName { get; set; }
                                public string LastName { get; set; }
                                public int Age { get; set; }
                                public string Phone { get; set; }

                                public override string ToString()
                                {
                                var sb = new StringBuilder();

                                sb.AppendFormat("Your name is: {0} {1} {2}", FirstName, Initial(MiddleName, true), LastName).AppendLine();
                                sb.AppendFormat("Your initials are: {0}{1}{2}", Initial(FirstName, false), Initial(MiddleName, false), Initial(LastName, false)).AppendLine();
                                sb.AppendFormat("Your age is: {0}", Age).AppendLine();
                                sb.AppendFormat("Your phone number is: {0}", Phone).AppendLine();

                                return sb.ToString();
                                }

                                private static string Initial(string input, bool dot)
                                {
                                if (String.IsNullOrEmpty(input))
                                return input;

                                if(input.Contains(" "))
                                return input.Split(' ').Aggregate("", (current, s) => current + s[0]);

                                return input[0] + (dot ? "." : "");
                                }
                                }

                                internal class KeyInput
                                {
                                public static string KeyIn(string scrtext)
                                {
                                Console.Write(scrtext);
                                var buffer = Console.ReadLine();
                                return buffer;
                                }
                                }

                                internal class Program
                                {
                                public static void Main(string args)
                                {
                                Console.WriteLine("Please enter data for one or more person(s)." + Environment.NewLine);

                                var people = new List<Person>();
                                var newInput = true;

                                while (newInput)
                                {
                                var person = GetNewPerson();
                                people.Add(person);
                                newInput = KeyInput.KeyIn("Add another person? (Y/N): ").ToLower().Equals("y");
                                }

                                foreach (var person in people)
                                Console.WriteLine(person.ToString() + Environment.NewLine);

                                Console.ReadKey();
                                }

                                public static Person GetNewPerson()
                                {
                                var first = KeyInput.KeyIn("Please enter your first name: ");
                                var middle = KeyInput.KeyIn("Please enter your middle name: ");
                                var last = KeyInput.KeyIn("Please enter your last name: ");
                                int age;

                                while (!int.TryParse(KeyInput.KeyIn("Please enter your age: "), out age))
                                Console.WriteLine("Invalid input, try again...");

                                var phone = KeyInput.KeyIn("Please enter your phone number: ");

                                return new Person { FirstName = first, MiddleName = middle, LastName = last, Age = age, Phone = phone };
                                }
                                }


                                Still feel free to comment, I'm learning myself! ;)






                                share|improve this answer



















                                • 4




                                  NewPerson() feels wrong in the KeyInput class. They are two completely separate operations.
                                  – Jeff Vanzella
                                  Mar 13 '13 at 15:55






                                • 2




                                  I don't like seeing while(true) - it makes me have to figure out why you're looping - I'd change it to while(!int.TryParse(KeyInput.keyIn("Please enter your age"), out age)) or use a well named variable. I'd also use sb.AppendFormat(...).AppendLine() but that's personal preference.
                                  – RobH
                                  Mar 13 '13 at 16:02












                                • I edited my answer based on your useful comments :)
                                  – Abbas
                                  Mar 13 '13 at 22:46












                                • Thank you for your effort to provide such a detailed insight into my code.
                                  – Nenad Bulatovic
                                  Mar 14 '13 at 9:41










                                • No problem, I hope it helped you further!
                                  – Abbas
                                  Mar 14 '13 at 10:27














                                2












                                2








                                2






                                Person



                                Split user-input from your class definition. It's not a good practice to mix the input in the definition. Try to decouple as much as possible. I also redefined the properties in the class:



                                public string FirstName { get; set; }
                                public string MiddleName { get; set; }
                                public string LastName { get; set; }
                                public int Age { get; set; }
                                public string Phone { get; set; }


                                Same goes for displaying the information about the person. It's not a good practice to write it to screen from within this class. Just override the ToString()-method and display this on screen. The FirstChar()-method is there to check if the name exists to take the first character of that name, otherwise return a spacer.



                                public override string ToString()
                                {
                                StringBuilder sb = new StringBuilder();
                                sb.AppendLine(String.Format("Your name is: {0} {1}. {2}", FirstName, FirstChar(MiddleName), LastName));
                                sb.AppendLine(String.Format("Your initials are: {0}{1}{2}", FirstChar(FirstName), FirstChar(MiddleName), FirstChar(LastName)));
                                sb.AppendLine(String.Format("Your age is: {0}", Age));
                                sb.AppendLine(String.Format("Your phone number is: {0}", Phone));

                                return sb.ToString();
                                }

                                private char FirstChar(string input)
                                {
                                return String.IsNullOrEmpty(input) ? ' ' : input[0];
                                }


                                Input



                                Since the input is not mixed in the Person-class we have to declare it somewhere else. In this example I put the input-code in the KeyInput class. The method returns an instance of the Person-class and if the user enters "exit", null is returned. This way we can later on catch if the user wants to stop.



                                public static Person NewPerson()
                                {
                                string first = KeyInput.keyIn("Please enter your first name: ");
                                if (first.ToLower().Equals("exit"))
                                return null;

                                string middle = KeyInput.keyIn("Please enter your middle name: ");
                                string last = KeyInput.keyIn("Please enter your last name: ");
                                int age = 0;

                                while (true)
                                {
                                try
                                {
                                age = Convert.ToInt32(KeyInput.keyIn("Please enter your age"));
                                break;
                                }
                                catch (ArgumentException)
                                {
                                Console.WriteLine("No value was entered");
                                }
                                catch (FormatException)
                                {
                                Console.WriteLine("You didn't entered a valid number");
                                }
                                catch (Exception)
                                {
                                Console.WriteLine("Something went wrong with the conversion.");
                                }
                                }

                                string phone = KeyInput.keyIn("Please enter your phone numbern");

                                return new Person { FirstName = first, MiddleName = middle, LastName = last, Age = age, Phone = phone };
                                }


                                Main



                                Since all previous code has changed, the logic of your Main will change too.



                                public static void Main()
                                {
                                Console.WriteLine("Please enter data for person(s). Enter EXIT to end.");

                                List<Person> people = new List<Person>();

                                while (true)
                                {
                                var person = KeyInput.NewPerson();

                                if(person == null)
                                break;

                                people.Add(person);
                                }

                                foreach (var person in people)
                                {
                                Console.WriteLine(person.ToString());
                                }
                                }


                                Summary



                                I'm not saying that my code is perfect in any way. Probably my code could be revised and corrected as well. I only want to show you the way how you decouple user-input from class-definitions, use proper variable names, bring a proper structure and logic in your code. Please feel free if to comment if anything's wrong with my code.



                                Edit:



                                Thanks to the valid comments I received, I edited the code. The posters of the comments were absolutely right. I've also rewritten the Initial()-method to a more correct logic. Here's the result in it's entirety:



                                internal class Person
                                {
                                public string FirstName { get; set; }
                                public string MiddleName { get; set; }
                                public string LastName { get; set; }
                                public int Age { get; set; }
                                public string Phone { get; set; }

                                public override string ToString()
                                {
                                var sb = new StringBuilder();

                                sb.AppendFormat("Your name is: {0} {1} {2}", FirstName, Initial(MiddleName, true), LastName).AppendLine();
                                sb.AppendFormat("Your initials are: {0}{1}{2}", Initial(FirstName, false), Initial(MiddleName, false), Initial(LastName, false)).AppendLine();
                                sb.AppendFormat("Your age is: {0}", Age).AppendLine();
                                sb.AppendFormat("Your phone number is: {0}", Phone).AppendLine();

                                return sb.ToString();
                                }

                                private static string Initial(string input, bool dot)
                                {
                                if (String.IsNullOrEmpty(input))
                                return input;

                                if(input.Contains(" "))
                                return input.Split(' ').Aggregate("", (current, s) => current + s[0]);

                                return input[0] + (dot ? "." : "");
                                }
                                }

                                internal class KeyInput
                                {
                                public static string KeyIn(string scrtext)
                                {
                                Console.Write(scrtext);
                                var buffer = Console.ReadLine();
                                return buffer;
                                }
                                }

                                internal class Program
                                {
                                public static void Main(string args)
                                {
                                Console.WriteLine("Please enter data for one or more person(s)." + Environment.NewLine);

                                var people = new List<Person>();
                                var newInput = true;

                                while (newInput)
                                {
                                var person = GetNewPerson();
                                people.Add(person);
                                newInput = KeyInput.KeyIn("Add another person? (Y/N): ").ToLower().Equals("y");
                                }

                                foreach (var person in people)
                                Console.WriteLine(person.ToString() + Environment.NewLine);

                                Console.ReadKey();
                                }

                                public static Person GetNewPerson()
                                {
                                var first = KeyInput.KeyIn("Please enter your first name: ");
                                var middle = KeyInput.KeyIn("Please enter your middle name: ");
                                var last = KeyInput.KeyIn("Please enter your last name: ");
                                int age;

                                while (!int.TryParse(KeyInput.KeyIn("Please enter your age: "), out age))
                                Console.WriteLine("Invalid input, try again...");

                                var phone = KeyInput.KeyIn("Please enter your phone number: ");

                                return new Person { FirstName = first, MiddleName = middle, LastName = last, Age = age, Phone = phone };
                                }
                                }


                                Still feel free to comment, I'm learning myself! ;)






                                share|improve this answer














                                Person



                                Split user-input from your class definition. It's not a good practice to mix the input in the definition. Try to decouple as much as possible. I also redefined the properties in the class:



                                public string FirstName { get; set; }
                                public string MiddleName { get; set; }
                                public string LastName { get; set; }
                                public int Age { get; set; }
                                public string Phone { get; set; }


                                Same goes for displaying the information about the person. It's not a good practice to write it to screen from within this class. Just override the ToString()-method and display this on screen. The FirstChar()-method is there to check if the name exists to take the first character of that name, otherwise return a spacer.



                                public override string ToString()
                                {
                                StringBuilder sb = new StringBuilder();
                                sb.AppendLine(String.Format("Your name is: {0} {1}. {2}", FirstName, FirstChar(MiddleName), LastName));
                                sb.AppendLine(String.Format("Your initials are: {0}{1}{2}", FirstChar(FirstName), FirstChar(MiddleName), FirstChar(LastName)));
                                sb.AppendLine(String.Format("Your age is: {0}", Age));
                                sb.AppendLine(String.Format("Your phone number is: {0}", Phone));

                                return sb.ToString();
                                }

                                private char FirstChar(string input)
                                {
                                return String.IsNullOrEmpty(input) ? ' ' : input[0];
                                }


                                Input



                                Since the input is not mixed in the Person-class we have to declare it somewhere else. In this example I put the input-code in the KeyInput class. The method returns an instance of the Person-class and if the user enters "exit", null is returned. This way we can later on catch if the user wants to stop.



                                public static Person NewPerson()
                                {
                                string first = KeyInput.keyIn("Please enter your first name: ");
                                if (first.ToLower().Equals("exit"))
                                return null;

                                string middle = KeyInput.keyIn("Please enter your middle name: ");
                                string last = KeyInput.keyIn("Please enter your last name: ");
                                int age = 0;

                                while (true)
                                {
                                try
                                {
                                age = Convert.ToInt32(KeyInput.keyIn("Please enter your age"));
                                break;
                                }
                                catch (ArgumentException)
                                {
                                Console.WriteLine("No value was entered");
                                }
                                catch (FormatException)
                                {
                                Console.WriteLine("You didn't entered a valid number");
                                }
                                catch (Exception)
                                {
                                Console.WriteLine("Something went wrong with the conversion.");
                                }
                                }

                                string phone = KeyInput.keyIn("Please enter your phone numbern");

                                return new Person { FirstName = first, MiddleName = middle, LastName = last, Age = age, Phone = phone };
                                }


                                Main



                                Since all previous code has changed, the logic of your Main will change too.



                                public static void Main()
                                {
                                Console.WriteLine("Please enter data for person(s). Enter EXIT to end.");

                                List<Person> people = new List<Person>();

                                while (true)
                                {
                                var person = KeyInput.NewPerson();

                                if(person == null)
                                break;

                                people.Add(person);
                                }

                                foreach (var person in people)
                                {
                                Console.WriteLine(person.ToString());
                                }
                                }


                                Summary



                                I'm not saying that my code is perfect in any way. Probably my code could be revised and corrected as well. I only want to show you the way how you decouple user-input from class-definitions, use proper variable names, bring a proper structure and logic in your code. Please feel free if to comment if anything's wrong with my code.



                                Edit:



                                Thanks to the valid comments I received, I edited the code. The posters of the comments were absolutely right. I've also rewritten the Initial()-method to a more correct logic. Here's the result in it's entirety:



                                internal class Person
                                {
                                public string FirstName { get; set; }
                                public string MiddleName { get; set; }
                                public string LastName { get; set; }
                                public int Age { get; set; }
                                public string Phone { get; set; }

                                public override string ToString()
                                {
                                var sb = new StringBuilder();

                                sb.AppendFormat("Your name is: {0} {1} {2}", FirstName, Initial(MiddleName, true), LastName).AppendLine();
                                sb.AppendFormat("Your initials are: {0}{1}{2}", Initial(FirstName, false), Initial(MiddleName, false), Initial(LastName, false)).AppendLine();
                                sb.AppendFormat("Your age is: {0}", Age).AppendLine();
                                sb.AppendFormat("Your phone number is: {0}", Phone).AppendLine();

                                return sb.ToString();
                                }

                                private static string Initial(string input, bool dot)
                                {
                                if (String.IsNullOrEmpty(input))
                                return input;

                                if(input.Contains(" "))
                                return input.Split(' ').Aggregate("", (current, s) => current + s[0]);

                                return input[0] + (dot ? "." : "");
                                }
                                }

                                internal class KeyInput
                                {
                                public static string KeyIn(string scrtext)
                                {
                                Console.Write(scrtext);
                                var buffer = Console.ReadLine();
                                return buffer;
                                }
                                }

                                internal class Program
                                {
                                public static void Main(string args)
                                {
                                Console.WriteLine("Please enter data for one or more person(s)." + Environment.NewLine);

                                var people = new List<Person>();
                                var newInput = true;

                                while (newInput)
                                {
                                var person = GetNewPerson();
                                people.Add(person);
                                newInput = KeyInput.KeyIn("Add another person? (Y/N): ").ToLower().Equals("y");
                                }

                                foreach (var person in people)
                                Console.WriteLine(person.ToString() + Environment.NewLine);

                                Console.ReadKey();
                                }

                                public static Person GetNewPerson()
                                {
                                var first = KeyInput.KeyIn("Please enter your first name: ");
                                var middle = KeyInput.KeyIn("Please enter your middle name: ");
                                var last = KeyInput.KeyIn("Please enter your last name: ");
                                int age;

                                while (!int.TryParse(KeyInput.KeyIn("Please enter your age: "), out age))
                                Console.WriteLine("Invalid input, try again...");

                                var phone = KeyInput.KeyIn("Please enter your phone number: ");

                                return new Person { FirstName = first, MiddleName = middle, LastName = last, Age = age, Phone = phone };
                                }
                                }


                                Still feel free to comment, I'm learning myself! ;)







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Mar 13 '13 at 22:46

























                                answered Mar 13 '13 at 12:52









                                Abbas

                                5,2731538




                                5,2731538








                                • 4




                                  NewPerson() feels wrong in the KeyInput class. They are two completely separate operations.
                                  – Jeff Vanzella
                                  Mar 13 '13 at 15:55






                                • 2




                                  I don't like seeing while(true) - it makes me have to figure out why you're looping - I'd change it to while(!int.TryParse(KeyInput.keyIn("Please enter your age"), out age)) or use a well named variable. I'd also use sb.AppendFormat(...).AppendLine() but that's personal preference.
                                  – RobH
                                  Mar 13 '13 at 16:02












                                • I edited my answer based on your useful comments :)
                                  – Abbas
                                  Mar 13 '13 at 22:46












                                • Thank you for your effort to provide such a detailed insight into my code.
                                  – Nenad Bulatovic
                                  Mar 14 '13 at 9:41










                                • No problem, I hope it helped you further!
                                  – Abbas
                                  Mar 14 '13 at 10:27














                                • 4




                                  NewPerson() feels wrong in the KeyInput class. They are two completely separate operations.
                                  – Jeff Vanzella
                                  Mar 13 '13 at 15:55






                                • 2




                                  I don't like seeing while(true) - it makes me have to figure out why you're looping - I'd change it to while(!int.TryParse(KeyInput.keyIn("Please enter your age"), out age)) or use a well named variable. I'd also use sb.AppendFormat(...).AppendLine() but that's personal preference.
                                  – RobH
                                  Mar 13 '13 at 16:02












                                • I edited my answer based on your useful comments :)
                                  – Abbas
                                  Mar 13 '13 at 22:46












                                • Thank you for your effort to provide such a detailed insight into my code.
                                  – Nenad Bulatovic
                                  Mar 14 '13 at 9:41










                                • No problem, I hope it helped you further!
                                  – Abbas
                                  Mar 14 '13 at 10:27








                                4




                                4




                                NewPerson() feels wrong in the KeyInput class. They are two completely separate operations.
                                – Jeff Vanzella
                                Mar 13 '13 at 15:55




                                NewPerson() feels wrong in the KeyInput class. They are two completely separate operations.
                                – Jeff Vanzella
                                Mar 13 '13 at 15:55




                                2




                                2




                                I don't like seeing while(true) - it makes me have to figure out why you're looping - I'd change it to while(!int.TryParse(KeyInput.keyIn("Please enter your age"), out age)) or use a well named variable. I'd also use sb.AppendFormat(...).AppendLine() but that's personal preference.
                                – RobH
                                Mar 13 '13 at 16:02






                                I don't like seeing while(true) - it makes me have to figure out why you're looping - I'd change it to while(!int.TryParse(KeyInput.keyIn("Please enter your age"), out age)) or use a well named variable. I'd also use sb.AppendFormat(...).AppendLine() but that's personal preference.
                                – RobH
                                Mar 13 '13 at 16:02














                                I edited my answer based on your useful comments :)
                                – Abbas
                                Mar 13 '13 at 22:46






                                I edited my answer based on your useful comments :)
                                – Abbas
                                Mar 13 '13 at 22:46














                                Thank you for your effort to provide such a detailed insight into my code.
                                – Nenad Bulatovic
                                Mar 14 '13 at 9:41




                                Thank you for your effort to provide such a detailed insight into my code.
                                – Nenad Bulatovic
                                Mar 14 '13 at 9:41












                                No problem, I hope it helped you further!
                                – Abbas
                                Mar 14 '13 at 10:27




                                No problem, I hope it helped you further!
                                – Abbas
                                Mar 14 '13 at 10:27











                                -2














                                I have a question?



                                In my project I wanted to generate a ID automatically by students first name character last name character and his birthday combination of this I want to generate I'd help please






                                share|improve this answer








                                New contributor




                                Faizshaikh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                Check out our Code of Conduct.























                                  -2














                                  I have a question?



                                  In my project I wanted to generate a ID automatically by students first name character last name character and his birthday combination of this I want to generate I'd help please






                                  share|improve this answer








                                  New contributor




                                  Faizshaikh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                  Check out our Code of Conduct.





















                                    -2












                                    -2








                                    -2






                                    I have a question?



                                    In my project I wanted to generate a ID automatically by students first name character last name character and his birthday combination of this I want to generate I'd help please






                                    share|improve this answer








                                    New contributor




                                    Faizshaikh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.









                                    I have a question?



                                    In my project I wanted to generate a ID automatically by students first name character last name character and his birthday combination of this I want to generate I'd help please







                                    share|improve this answer








                                    New contributor




                                    Faizshaikh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.









                                    share|improve this answer



                                    share|improve this answer






                                    New contributor




                                    Faizshaikh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.









                                    answered 34 mins ago









                                    Faizshaikh

                                    1




                                    1




                                    New contributor




                                    Faizshaikh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.





                                    New contributor





                                    Faizshaikh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.






                                    Faizshaikh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Code Review Stack Exchange!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        Use MathJax to format equations. MathJax reference.


                                        To learn more, see our tips on writing great answers.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f23835%2fdisplaying-a-persons-personal-information-with-formatting%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Morgemoulin

                                        Scott Moir

                                        Souastre