Search code examples
c#.netgettypenameof

Object.GetType() also returning project name


Trying to override ToString() and use the GetType() to return the type of the object being used. It is returning the information but it includes the NameSpace. The question is how can I strip off the NameSpace and only display the object name. Here is my code:

namespace Trial
{
   class Testing
   {
      static void Main(string[] args)
      {
         //Variables
         Person[] objectPerson = new Person[5]; //create an array of references
         objectPerson[0] = new Person(10, "John", 35, 1200.00);
         objectPerson[1] = new Person(20, "Jill", 30, 2400.00);
         objectPerson[2] = new Person(30, "Joann", 40, 600.00);
         objectPerson[3] = new Person(40, "Jimmy", 25, 4800.00);
         objectPerson[4] = new Person(50, "Jamie", 45, 300.00);

         for (int y = 0; y < objectPerson.Length; ++y)
         {
            Console.WriteLine(objectPerson[y].ToString());
         }

         Console.Write("\nPress any key to exit . . .");
         Console.ReadKey();
      }
   }
   class Person
   {
      //Data fields
      private int number;
      private string name;
      private int age;
      private double amountDue;

      //Constructors
      public Person(): this(9,"ZZZ",0,0.00)
      {
      }
      public Person(int _Number, string _Name, int _Age, double _AmountDue)
      {
         Number = _Number;
         Name = _Name;
         Age = _Age;
         AmountDue = _AmountDue;
      }
      //Properties
      public int Number
      { 
         get { return number; }
         set { number = value; }
      }
      public string Name
      {
         get { return name; }
         set { name = value; }
      }
      public int Age
      {
         get { return age; }
         set { age = value; }
      }
      public double AmountDue
      {
         get { return amountDue; }
         set { amountDue = value; }
      }

      //Overrides
      public override string ToString()
      {
         return(this.GetType() + ": " + this.Number +  " - " + this.Name + " (" + this.Age.ToString() + "yo) | The total annual ammount is: " + this.AmountDue.ToString("C") + " and the quarterly payment is " + (this.AmountDue / 4).ToString("C"));
      }
   }
}

Solution

  • You're looking for GetType().Name