Tostring csharp best practice envelope

Asked

Viewed 65 times

-1

I see some programmers choosing to overwrite ToString in C# among some cases, my doubt, it is a bad practice to override this in specific or even depends on the programmer decide?

Example:

public string FirstName { get; private set; }
public string LastName { get; private set; }

public override string ToString()
{
    return $"{FirstName} {LastName}";
}
  • What do you mean by "method reserved"?

  • I improved/focused the question. Referring to whether it is a good or bad practice to override in Tostring or is it dev choice and situation.

  • 2

    It depends, what is the purpose in overriding this method? There is the need even?

  • This code belongs to another person, in which I have no contact to know why this implementation and code posted is the whole class.

  • In my view, it loses total coherence to overwrite it, for a simple ToString is not pointing out that the full name will be returned. However the concept of overwriting the ToString creates a dubiousness for me to know if there are cases where it can be a good practice or not.

  • 1

    Related: https://answall.com/q/212754/112052 <-- although in Java, the general idea is the same (but you can also see here, this yes specific to C#)

Show 1 more comment

2 answers

1


Being direct is more a matter of objectivity, to override the method is not wrong or right, it all depends on the intuition of your project, whether there is need or not, but when it comes to good practices the ideal is always to extend the functionalities and not to overwrite them, but I believe that also we can not take to iron and fire everything then worth a joint evaluation of teammate.

1

As best practices we should always avoid a superscript. Even more so in the Tostring() method, which will inevitably be widely used in your project.

Although Microsoft shows you how to do it, it doesn’t mean it’s good practice but as an example.

https://docs.microsoft.com/pt-br/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method

You can use the Stringextensions class to create custom methods to work with strings:

public static class StringExtensions
{
    public static string ToCompleteFullName(this string input)
    {
        return $"{input} {FirstName} {LastName}";
    }
}

And to call the method would be so simple:

string teste = "Full name:";

teste = teste.ToCompleteFullName();

  • And who defines what is or is not a "good practice"?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.