Alan2
Alan2

Reputation: 24572

How can I add a new method to FormattedString?

In my C# code I use this kind of construct many times:

FormattedString s = new FormattedString();
s.Spans.Add(new Span { Text = "On the ", ForegroundColor = Color.FromHex("555555") });
s.Spans.Add(new Span { Text = "settings", ForegroundColor = Color.Blue });

I would like to simplify this to something like:

FormattedString s = new FormattedString();
s.Spans.AddGray("On the ");
s.Spans.AddBlue("settings");

or even better

s.AddGray("On the ");
s.AddBlue("settings");

Is there a way that I can do this by somehow extending the capabilities of a FormattedString?

Upvotes: 2

Views: 113

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

You need a couple of extension methods:

public static void AddGray(this FormattedString formattedString, string text)
    => formattedString.Add(text, Color.FromHex("555555"));

public static void AddBlue(this FormattedString formattedString, string text)
    => formattedString.Add(text, Color.Blue);

Common logic is moved to another extension method which allows specifying color:

public static void Add(this FormattedString formattedString, string text, Color color)
    => formattedString.Spans.Add(new Span { Text = text, ForegroundColor = color });

Then you can add colored spans:

s.AddGray("On the ");
s.AddBlue("settings");
s.Add("imprtant", Color.Red);  

Note that I would make names of methods more descriptive - AddGraySpan, AddBlueSpan, AddSpan. I would also return original FormattedString instance from each extension method. That would allow you to use fluent API:

var s = new FormattedString().AddGraySpan("On the ").AddBlueSpan("settings");

Sample of implementation:

public static FormattedString AddSpan(this FormattedString formattedString,
   string text, Color color)
{
    formattedString.Spans.Add(new Span { Text = text, ForegroundColor = color });
    return formattedString;
}      

Upvotes: 5

sdgfsdh
sdgfsdh

Reputation: 37095

Yes, you can use extension methods.

using System.Linq;
using System.Text;
using System;

namespace CustomExtensions
{
    public static class FormattedStringExtension
    {
        public static void AddGray(this FormattedString formattedString, string x)
        {
            // TODO: Do something
        }

        public static void AddBlue(this FormattedString formattedString, string x)
        {
            // TODO: Do something
        }

        // etc... 
    }
}

Upvotes: 0

Related Questions