Search code examples
c#ooppropertiesoverridingtostring

C# properties and "tostring" method


I was trying to understand properties better and I came across this page with this example:

https://www.tutorialspoint.com/csharp/csharp_properties.htm

using System;
namespace tutorialspoint {
class Student {
  private string code = "N.A";
  private string name = "not known";
  private int age = 0;
  
  // Declare a Code property of type string:
  public string Code {
     get {
        return code;
     }
     set {
        code = value;
     }
  }
  
  // Declare a Name property of type string:
  public string Name {
     get {
        return name;
     }
     set {
        name = value;
     }
  }
  
  // Declare a Age property of type int:
  public int Age {
     get {
        return age;
     }
     set {
        age = value;
     }
  }
  public override string ToString() {
     return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
  }
}

class ExampleDemo {
  public static void Main() {
  
     // Create a new Student object:
     Student s = new Student();
     
     // Setting code, name and the age of the student
     s.Code = "001";
     s.Name = "Zara";
     s.Age = 9;
     Console.WriteLine("Student Info: {0}", s);
     
     //let us increase age
     s.Age += 1;
     Console.WriteLine("Student Info: {0}", s);
     Console.ReadKey();
  }
}
}

output: Student Info: Code = 001, Name = Zara, Age = 9

I don't understand how the first example is able to output the whole line written in the class "student". In the main method, we are using "s" which is an object created in the class "exampledemo". How is it able to call a method from another class? I guess it's something related to inheritance and polymorphism (I googled the override keyword) but it seems to me that the two classes are indipendent and not a subclass of the other. I'm a total beginner at programming and probably quite confused.


Solution

  • s is of type Student (as declared on the first line of Main()). Therefore one can call a method on the object to modify it or print it. When you do s.Name = "Zara"; you are already calling a method on Student to update it (technically, a method and a property are the same, they only differ by syntax).

    The line Console.WriteLine("Student Info: {0}", s); is actually the same as Console.WriteLine("Student Info: " + s.ToString());. The compiler allows writing this in a shorter form, but internally the same thing happens.