Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Define a class Person that has name, age and email. The name and age are mandatory. The email is optional. Define properties that accept non-empty name and age in the range [1 ... 100]. In case of invalid arguments, throw an exception. Define a property for the email that accepts either null or non-empty string containing '@'. Define two constructors. The first constructor should take name, age and email. The second constructor should take name and age only and call the first constructor. Implement the ToString() method to enable printing persons at the console. */
- namespace _01.Persons
- {
- using System;
- class Person
- {
- #region Fields
- private string name;
- private byte age;
- private string email;
- #endregion
- #region Constructor Chaining
- public Person(string name, byte age, string email)
- {
- this.Name = name;
- this.Age = age;
- this.Email = email;
- }
- public Person(string name, byte age)
- : this(name, age, null)
- {
- }
- #endregion
- #region Properties
- public string Name
- {
- get { return this.name; }
- set
- {
- if (string.IsNullOrEmpty(value))
- {
- throw new ArgumentException("Invalid name!");
- }
- this.name = value;
- }
- }
- public byte Age
- {
- get { return this.age; }
- set
- {
- if (value < 1 || value > 100)
- {
- throw new ArgumentException("Invalid age!");
- }
- this.age = value;
- }
- }
- public string Email
- {
- get { return this.email; }
- set
- {
- if (!string.IsNullOrEmpty(value) && value.IndexOf('@') == -1)
- {
- throw new ArgumentException("Invalid email!");
- }
- this.email = value;
- }
- }
- #endregion
- public override string ToString()
- {
- return string.Format("{0} is {1} years old. Email: {2}",
- this.Name, this.Age, this.Email ?? "none");
- }
- }
- class Persons
- {
- static void Main(string[] args)
- {
- Person p1 = new Person("Svetlin", 36);
- Console.WriteLine(p1);
- Person p2 = new Person("Nakov", 36, "nakov@gmail.com");
- Console.WriteLine(p2);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement