Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace Person
- {
- /*
- * Task 4
- * Create a class Person with two fields – name and age.
- * Age can be left unspecified (may contain null value.
- * Override ToString() to display the information of a person and if age is not specified – to say so.
- * Write a program to test this functionality.
- */
- public class Person
- {
- //Fields
- private string name;
- private int? age;
- //Constructors
- public Person(string name)
- {
- this.Name = name;
- }
- public Person(string name, int? age)
- : this(name)
- {
- this.Age = age;
- }
- //Properties
- public string Name
- {
- get { return name; }
- set
- {
- if (string.IsNullOrEmpty(value))
- {
- throw new ArgumentException("A Person must have a name!");
- }
- name = value;
- }
- }
- public int? Age
- {
- get { return age; }
- set
- {
- if (value < 0 || value > 150)
- {
- throw new ArgumentException(" This is not a possible human age!");
- }
- age = value;
- }
- }
- //Methods
- public override string ToString()
- {
- if (this.age == null)
- {
- return string.Format("Person name is: {0} , age unknown.", this.Name);
- }
- else
- {
- return string.Format("Person name is: {0} , age {1}.", this.Name, this.Age);
- }
- }
- }
- //Test person class
- public class TestPerson
- {
- public static void Main()
- {
- Person johny = new Person("Johny");
- Console.WriteLine(johny);
- johny.Age = 54;
- Console.WriteLine(johny);
- johny.Age = null;
- Console.WriteLine(johny);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment