Classes convertor

77 Views Asked by At

I have the following class People:

class People
{
    public enum Gender
    {
        Man = 'w',
        Woman = 'f'
    }

    public struct Person
    {
        public string First, Last;
        public Gender Gender;
        public int Age;
        public float Height, Weight;
    }

    public struct Group
    {
        public int Members;
        public string Name;
    }
}

Now, we are located in the class Program:

class Program
{
    static void Main( string[] args )
    {
        People.Person p = new People.Person();

        p.First = "Victor";
        p.Last = "Barbu";
        p.Age = 14;
        p.Height = 175;
        p.Weight = 62;
        p.Gender = People.Gender.Man;

        Console.ReadLine();
    }
}

I want to put a line like this:

Console.Write( x.toString() );

How can I customize the x.toString() method, so the result to be the following in the Console

Victor Barbu
14 years
Man
175 cm
62 kg

?

Thanks in advance!

3

There are 3 best solutions below

0
On

Just overrive the ToString() method

    public override string ToString()
    {
        // return the value you want here.
    }
0
On

You want to override the ToString method in the Person class. See: http://msdn.microsoft.com/en-us/library/ms173154(v=vs.80).aspx

In your case

public class Person
{
   // Snip
   public override string ToString()
   {
       return this.First + " " + this.Last; 
   }
}

If you then do

Console.WriteLine(person.ToString()); 

The expected output would be the first and last name, you can obviously extend this to include your other fields and line breaks, etc.

Side note; what you are doing is really "pretty printing" I would suggest creating a static method "public static string PrettyPrintPerson(Person p)" or similar, to deal with textual formatting of the class.

0
On
class People 
{ 

    public override string ToString()
    {
        //This will return exactly what you just put down with line breaks
        // then just call person.ToString()
        return string.format("{1} {2}{0}{3} years{0}{4}{0}{5} cm{0}{6} kg", Environment.NewLine,
            First, Last, Age, Gender, Height, Weight);
    }
}