Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override .ToString()

Tags:

c#

overriding

I would like to override the .ToString() function so that whenever I get a double it outputs only 5 digits after the decimal point.

How do I reffer to the object the .ToString is working on, inside the override function? In other words what shell I put instead of the XXX in the following code?

public override string ToString()
{
    if (XXX.GetType().Name == "Double")
        return (Math.Round(XXX, 5));
}
like image 541
Eli Avatar asked Jan 21 '10 13:01

Eli


3 Answers

Why not just use the built-in formatting?

var pi = 3.14159265m;
Console.WriteLine(pi.ToString("N5"));
-> "3.14159"

For reference I like the .NET Format String Quick Reference by John Sheehan.

like image 95
Jonas Elfström Avatar answered Nov 05 '22 01:11

Jonas Elfström


You can't override a method for a different type - basically you can't stop double.ToString doing what it does. You can, however, write a method which takes a double and formats it appropriately.

like image 34
Jon Skeet Avatar answered Nov 05 '22 00:11

Jon Skeet


As Jon pointed out, you can't override Double.ToString. You can create an extension method for double type that helps you do this:

public static class DoubleExtensions {
   public static string ToStringWith5Digits(this double x) { ... }
}

and use it like:

double d = 10;
string x = d.ToStringWith5Digits(); 
like image 20
mmx Avatar answered Nov 05 '22 00:11

mmx