Search code examples
c#visual-studioclassreturnoverriding

Public override string more returns


School asks me to use the public override string. I would like to have something like this:

lbl_Name.Text = ToString(*Field: Naam from class Gebruikerklasse*)
lbl_Surname.Text = ToString(*Field: Achternaam from class Gebruikersklasse*)

I have multiple fields in my class, but I want to return just a few of them. Do I need different methods or can I do it with just one method and more returns with some if statements and booleans?

This is what I have now:

 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace BurnThatFat
    {
        class Gebruikerklasse
        {
            public string Naam;
            public string Achternaam;
            public int Leeftijd;
            public string Geslacht;
            public int Huidiggewicht;
            public int Streefgewicht;
            public string Gebruikersnaam;
            public string Wachtwoord;

            public override string ToString()
            {
                return Naam;

            }
// I want to use the same method again but this time for another field.


 public override string ToString()
        {
            return Gebruikersnaam;
        }

    }

}

Solution

  • I suggest implementing IFormattable interface:

        class Gebruikerklasse {
          ...
    
          // "A" - Achternaam
          // "G" - Gebruikersnaam
          // "N" - Naam
          // null, empty - default ToString format  
          public string ToString(string format, IFormatProvider formatProvider) {
            if (string.IsNullOrEmpty(format))
              return ToString(); 
            else if ("N".Equals(format, StringComparison.OrdinalIgnoreCase))
              return Naam;
            else if ("A".Equals(format, StringComparison.OrdinalIgnoreCase))
              return Achternaam;
            else if ("G".Equals(format, StringComparison.OrdinalIgnoreCase))
              return Gebruikersnaam;
            else
              throw new FormatException($"Unknown format '{format}'");
          }
    
          public string ToString(string format) {
            return ToString(format, CultureInfo.CurrentCulture);
          }
    
          public override string ToString() {
            return Gebruikersnaam;
          }
        }
    

    And so you can put:

        Gebruikerklasse instance = new Gebruikerklasse();
    
        lbl_Name.Text = instance.ToString("G");
        lbl_Surname.Text = instance.ToString("A");