Home > database >  Call a user-method that gets and returns a string just like most of the String Class methods in .NET
Call a user-method that gets and returns a string just like most of the String Class methods in .NET

Time:10-27

I have been trying to make a method that does a "string cleaning process" and wanted to use it like one would use a simple string.Trim() or string.Normalize().

Method

public string ToFriendlyDOSNameString(string input)
{
    Regex whitespaces = new Regex(".*?([ ]{2,})");
    input = input.Normalize().Replace("\\", " ").Replace("/", " ").Replace("\"", " ")
                             .Replace("*", " ").Replace(":", " ").Replace("?", " ")
                             .Replace("<", " ").Replace(">", " ").Replace("|", " ")
                             .Replace("!", " ").Replace(".", " ").Replace("'", " ").Trim();
    string clone = input;
    foreach (Match match in whitespaces.Matches(input))
    {
        clone = clone.Replace(match.Groups[1].Value, " ");
    }
    input = clone;
    return input;
}

And what I am looking for is a way to use this method in the following manner:

string example = "Some Random Text";
example = example.ToFriendlyDOSNameString();

For reference, I'm currently using this on a console application and this method is placed right under the "main method", I don't exactly know where I'd place a method for it to have the behavior I want it to have...

CodePudding user response:

Several things are missing from your extension method:

  • The method needs to be static;
  • The string parameter should use the this keyword.

Example:

public static class MyExtensions
{
    public static string ToFriendlyDosNameString(this string input)
    {
        // Your logic.
    }
}

More information:

Extension Methods (C# Programming Guide)

CodePudding user response:

public static class Utilities {
    public static string ToFriendlyDOSName(this string str) {
        str = "new friendly value";
        // modify the value according to your logic
        return str;
    }
}

then you can use it like you mentioned

string myName = "unfriendly name";
myName.ToFriendlyDOSName();
  •  Tags:  
  • c#
  • Related