archangelmihail

Person

Feb 19th, 2014
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.08 KB | None | 0 0
  1. using System;
  2. namespace Person
  3. {
  4.     /*
  5.      * Task 4
  6.      * Create a class Person with two fields – name and age.
  7.      * Age can be left unspecified (may contain null value.
  8.      * Override ToString() to display the information of a person and if age is not specified – to say so.
  9.      * Write a program to test this functionality.
  10.      */
  11.  
  12.     public class Person
  13.     {
  14.         //Fields
  15.         private string name;
  16.         private int? age;
  17.         //Constructors
  18.         public Person(string name)
  19.         {
  20.             this.Name = name;
  21.         }
  22.         public Person(string name, int? age)
  23.             : this(name)
  24.         {
  25.             this.Age = age;
  26.         }
  27.         //Properties
  28.         public string Name
  29.         {
  30.             get { return name; }
  31.             set
  32.             {
  33.                 if (string.IsNullOrEmpty(value))
  34.                 {
  35.                     throw new ArgumentException("A Person must have a name!");
  36.                 }
  37.                 name = value;
  38.             }
  39.         }
  40.         public int? Age
  41.         {
  42.             get { return age; }
  43.             set
  44.             {
  45.                 if (value < 0 || value > 150)
  46.                 {
  47.                     throw new ArgumentException(" This is not a possible human age!");
  48.                 }
  49.                 age = value;
  50.             }
  51.         }
  52.         //Methods
  53.         public override string ToString()
  54.         {
  55.             if (this.age == null)
  56.             {
  57.                 return string.Format("Person name is: {0} , age unknown.", this.Name);
  58.             }
  59.             else
  60.             {
  61.                 return string.Format("Person name is: {0} , age {1}.", this.Name, this.Age);
  62.             }
  63.         }
  64.     }
  65.  
  66.     //Test person class
  67.     public class TestPerson
  68.     {
  69.         public static void Main()
  70.         {
  71.             Person johny = new Person("Johny");
  72.             Console.WriteLine(johny);
  73.             johny.Age = 54;
  74.             Console.WriteLine(johny);
  75.             johny.Age = null;
  76.             Console.WriteLine(johny);
  77.         }
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment