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
Three main approaches:
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.
public static string ToStringOrEmpty(this int i)
{
return (0==i)? string.Empty : i.ToString();
}
class X
{
int member;
public string getMember() { return (0==member)? string.Empty : member.ToString();
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With