Kraang Prime
Kraang Prime

Reputation: 10479

Error CS1109 Extension methods must be defined in a top level static class; Patterns is a nested class

I would like to extend the string object and have those extensions part of a nested class, however directly doing it this way :

public static class StringExtensions
{
    public static class Patterns
    {
        public static string NumbersOnly(this string s)
        {
            return new String(s.Where(Char.IsDigit).ToArray());
        }
    }
}

... gives the error as stated for the title of this post.

How can I write this differently so that when I call it, it can be called like this :

string s = "abcd1234";
s = s.Patterns.NumbersOnly();

I know I can move NumbersOnly as a direct child of StringExtensions to make the error go away, however my intention is to organize the methods into categories which will have a lot of methods. In this example, NumbersOnly is just one of about 40 pattern matches I intend to have there and I do not wish to clutter of the root of the object with methods like: PatternNumbersOnly or NumbersOnly etc.

Note: This question is different than questions like this one as I am not asking why this problem exists, I am looking for a workaround so that I can have the functionality or similar functionality which the reason of this error is denying me from.

Upvotes: 0

Views: 1271

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

You can't - there are no "extension properties".

The best you can get - s.Patterns().NumbersOnly() by introducing intermediate class to return from Patterns extension method.

Sample puts all methods in single class, but you can organize them any way you want to different classes as long as extensions methods satisfy "defined in a top level static class":

public static class StringExtensions
{
  public class PatternsX
  { 
    public string Value {get;set;}
  }

  public static PatternsX Patterns(this string s)
  {
    return new PatternsX { Value = s};
  }

  public static string NumbersOnly(this PatternsX s)
  {
    return new String(s.Value.Where(Char.IsDigit).ToArray());
  }
}

....    
Console.WriteLine("123ver".Patterns().NumbersOnly()); // results in 123

Upvotes: 5

Related Questions