Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override ToString() for an int element in a class

Tags:

c#

.net

i would like to override the ToString() method for an int (that is a part of a class) so that if the value of the int is 0, the ToString() should return an empty string "".Can this be done?

UPDATE It would be easy to just create a

public string AmountToString {
    get { if (Amount != 0) return Amount.ToString(); else return ""; }
}

i was just curious to see if it could be implemented (the ToString() ) on an primite type

like image 369
Alex Avatar asked Dec 10 '22 04:12

Alex


2 Answers

Three main approaches:

Employ a (custom) Format provider

So you can use i.ToString(formatprovider);

Edit I think I found a custom format string one that works with the default .NET number format provider:

i.ToString("0;-0;"); // works

Another sample lifted from the page on The ";" Section Separator:

i.ToString("##;(##);**Zero**"); // would return "**Zero** instead

Tip:

You can download the Format Utility, an application that enables you to apply format strings to either numeric or date and time values and displays the result string.

Extension method

public static string ToStringOrEmpty(this int i)
{
    return (0==i)? string.Empty : i.ToString();
}

Accessor Helper:

class X
{ 
      int member;

      public string getMember() { return (0==member)? string.Empty : member.ToString();
}
like image 72
sehe Avatar answered Dec 27 '22 14:12

sehe


Unfortunately no. You need to have access to the class code to override any methods or properties, including the ToString method. As int is a primative type, you are not able to change the classes code (not with ease and not reliably anyway).

Your best option would be to create an Extension method:

public static class IntExtensions
{
    public static ToStringOrEmpty(this int value)
    {
        return value == 0 ? "" : value.ToString();
    }
}
like image 45
Connell Avatar answered Dec 27 '22 15:12

Connell