TazmanianTad
TazmanianTad
CC#
Created by TazmanianTad on 11/5/2023 in #help
❔ Allowing a user to use a custom format in string.format
Hey all, I currently allow users to use a custom format for basic args defined in my application, so they can use {0}-{5} in a string entry. I am trying to figure out how give them slightly more control by doing something like {5:(x)} where if 5 was an arg(sometimes it is, some times it is not) it would show up as (555) However, I would like them to be able to use whatever text they would like, almost like a format within a format like : {5:({5})} for several reasons: The variable 5 will always be a double, but it could be 1, 1.6666, 0.22222222222222, etc, so the length is unknown They may or may not want to use ()'s, they may want various other formats, not just ()'s Can anyone help me figure out how to accomplish this? I have tried using a custmo formatter to basically format the format like this, however I was unable to succeed in getting this working..
public class MyFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}

public string Format(string fmt, object arg, IFormatProvider formatProvider)
{
if (arg == null) return string.Empty;

if (fmt == "x")
fmt = fmt.Substring(1);

if (arg is IFormattable)
return ((IFormattable)arg).ToString(fmt, CultureInfo.CurrentCulture);

return arg.ToString();
}
}
public class MyFormatter : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}

public string Format(string fmt, object arg, IFormatProvider formatProvider)
{
if (arg == null) return string.Empty;

if (fmt == "x")
fmt = fmt.Substring(1);

if (arg is IFormattable)
return ((IFormattable)arg).ToString(fmt, CultureInfo.CurrentCulture);

return arg.ToString();
}
}
Using this formatter I tried essentially: string.Format(new MyFormatter(), "{0:x({0})}", 1.1) in the hopes of receiving: (1.1) output. Unforetunetly I receive no output.
3 replies