2

I want to show custom ToString() formats in intellisense like DateTime.ToString() below.

enter image description here

Below is sample code where I would like to show "a" or "b" in intellisense when someone types myObject.ToString("").

public class MyClass : IFormattable
{
    public string ToString(string format, IFormatProvider formatProvider)
    {
        switch (format)
        {
            case "a":
                return "A";
            case "b":
                return "B";
            default:
                return "A";
        }
    }
}
imlokesh
  • 2,506
  • 2
  • 22
  • 26

1 Answers1

3

You can use XML Doc Comments for this.

For example, for your ToString() something along these lines:

public class MyClass : IFormattable
{
    /// <summary>Converts this to a formatted string.</summary>
    /// <param name="format">
    ///   A format string. This may have the following values:
    ///   <list type="table">
    ///     <listheader>
    ///       <term>Format strings</term>
    ///     </listheader>
    ///     <item>
    ///       <term>"a"</term>
    ///       <description>Format using "a"</description>
    ///     </item>
    ///     <item>
    ///       <term>"b"</term>
    ///       <description>Format using "b"</description>
    ///     </item>
    ///   </list>
    /// </param>
    /// <param name="formatProvider">A format provider.</param>
    /// <returns>The formatted string.</returns>

    public string ToString(string format, IFormatProvider formatProvider)
    {
        switch (format)
        {
            case "a":
                return "A";
            case "b":
                return "B";
            default:
                return "A";
        }
    }
}
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • 1
    Hello this works well but it does not generate intellisense like the one in screenshot. I'd like to know if something like the screenshot in question is possible. – imlokesh Sep 20 '20 at 13:20
  • 1
    @imlokesh As far as I know, the built-in intellisense is special-cased, so XML Doc comments is the closest you're likely to get. – Matthew Watson Sep 20 '20 at 13:21
  • 2
    @imlokesh, if you want to extend intellisense for tostring(), you have to create a vsix project to [implement some intellisense apis](https://stackoverflow.com/questions/10460138/custom-intellisense-extension), it is a vs sdk project's job and it is a bit complex. So Matthew is a closer and easier way to achieve that. – Mr Qian Sep 22 '20 at 08:00
  • @imlokesh, if his answer helps you handle the issue, you could consider accept it. – Mr Qian Sep 22 '20 at 08:00
  • @PerryQian-MSFT i plan on doing that... just waiting to see if someone else has anything else to add. – imlokesh Sep 22 '20 at 10:04
  • Sure, that is your choice:) – Mr Qian Sep 22 '20 at 10:05