In the current article, I will show you the code of a solution of one homework from the SoftUni (www.softuni.bg). The solution is built in YouTube and you may take a look at it, if you want to hear me speaking in English.
So, here comes the problem:
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 argument, 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.
The code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem1Persons { class People { static void Main () { List people = new List() { new Person("Vitosh",29), new Person("Vitosh",29,"vitosh@myemail.com"), new Person("Vitosh Doynov",129), new Person("VitoshAcademy",12,"vitosh@myemail.com") }; people.ForEach(vit=>Console.WriteLine(vit.ToString())); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem1Persons { class Person { private string name; private int age; private string email; public Person(string name, int age, string email) { this.Age = age; this.Name = name; this.Email = email; } public Person(string name, int age):this(name, age,null) { } public string Name { get { return this.name; } set { if (string.IsNullOrEmpty(value)) throw new ArgumentException("Your name is not valid"); this.name = value; } } public string Email { get { return this.email; } set { if (value != null && (value.Length == 0 || !value.Contains("@"))) throw new ArgumentException("Your e-mail is not valid!"); this.email = value; } } public int Age { get { return this.age; } set { if (value < 1 || value > 200) throw new ArgumentException("Your age is not valid!"); this.age = value; } } public override string ToString() { return string.Format("Hi! My name is {0}, I am {1} old ", this.Name,this.Age) + (this.Email==null?" And I do not have an e-mail...": "email: "+this.Email); } } } |
And finally, the video:
Enjoy it!