C# – Defining Classes – SoftUni Homework

Some time ago I wrote a homework, concerning building classes. The easiest part of it looked like this as a task:

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.

After some time, I managed to create the following main method:

What it does is the following:


The question is how? 🙂

The answer is quite obvious for anyone dealing with Object Oriented Programming – we create an object and we simply call it with the “ToString” from the LINQ.

Let’s see what we got here.

  • We should have a class, named “Person” with three properties – name, age and e-mail.
  • The we need 2 constructors – one accepting only name and age and one accepting email, age and name. To make it more interesting, the bigger one inherits the smaller.
  • The third thing we should do is to define the get and the set of the three properties.
  • At last, we override the ToString method. This means, that in our class ToString would do what we want and not what .Net usually expects from it. In the ToString method there is a checker whether we have E-mail or not.

So, this is how the code looks like! Enjoy it if you can 🙂


Tagged with: , ,