I am searching for a way how to avoid verbose overloads in case of a method that 1) will always convert parameter to string and 2) should be available for passing other types as parameter.
As always a picture snippet is worth a thousand words and found the following solution resp. example: (i.e. by using an object parameter, which is cast to IFormattable for passing invariant culture)
public static string AppendHexSuffix(this object hexNumber)
{
string hexString = (hexNumber as IFormattable)? // Cast as IFormattable to pass inv cul
.ToString(null, CultureInfo.InvariantCulture) ?? hexNumber.ToString();
if (!hexString.StartsWith("0x", true, CultureInfo.InvariantCulture)
&& !hexString.EndsWith("h", true, CultureInfo.InvariantCulture))
{
hexString += "h"; // Append hex notation suffix, if missing prefix/suffix
}
return hexString;
}
Although, as far as I've tested, it seems to work fine (correct me if I'm missing something), the upper code doesn't look particularly straight-forward to me and would prefer a more intuitive-looking solution.
Final Question: is there any other more elegant way how to solve this 1) without using the upper object parameter approach and 2) without explicitly declare an overload for each type?
Note: the upper snippet should be take strictly as an example, since the if
-statement part, does make sense only in case a "real" string is passed as parameter.
EDIT: After taking into account the answers + comments I've got, and after some more trials, the following final implementation seems to be best-suited for my case:
/// <summary>
/// Converts any type to string and if hex notation prefix/suffix is missing
/// yet still a valid hex number, then appends the hex suffix
/// </summary>
/// <param name="hexNumber">Takes a string, decimal and other types as parameter</param>
/// <returns>Returns input object content as string with hex notation</returns>
public static string AppendHexSuffix<T>(this T hexNumber)
{
// Cast as IFormattable to pass hex format ("X") & invariant culture
var hexString = (hexNumber as IFormattable)?
.ToString("X", CultureInfo.InvariantCulture).Trim() ?? hexNumber.ToString().Trim();
int unused;
if (!hexString.StartsWith("0x", true, CultureInfo.InvariantCulture)
&& !hexString.EndsWith("h", true, CultureInfo.InvariantCulture)
&& int.TryParse( // No hex prefix/suffix, but still a valid hexadecimal number
hexString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out unused))
{
hexString += "h";
}
return hexString;
}
By this, it also should ignore parameters/objects where hex format makes no sense, as pointed out in the comment from @InBetween. Noteworthy mistake: forgot the "X" format for the first .ToString() call.