Reputation: 9881
Adding extension methods is simple via:
public static class MyStringExtensions
{
public static string MyMethodOne(this string aSource)
{
return aSource += "My Method One";
}
public static string MyMethodTwo(this string aSource)
{
return aSource += "My Method Two";
}
}
and callable as:
"some string".MyMethodOne();
"some string".MyMethodTwo();
However I have a large number of method and want to "group them" using a static class container:
public static class MyStringExtensionsGroup
{
public static string MethodOne(string aSource)
{
return aSource += "My Method One";
}
public static string MethodTwo(string aSource)
{
return aSource += "My Method Two";
}
}
So assuming I somehow expose My : MyStringExtensionsGroup
as a string extension I could end up calling things with the following convention (note period after My
):
"some string".My.MethodOne();
"some string".My.MethodTwo();
and say I had another grouping called '''MyOtherGroup''' I could then do:
"some string".MyOtherGroup.MethodOne();
"some string".MyOtherGroup.MethodTwo();
Is any "grouping" of extension methods possible with what C# currently provides?
Upvotes: 0
Views: 100
Reputation: 81583
Extensions methods can't be nested, however with a lot of mindless fiddling you could create your own fluent syntax.
Extensions
public static class MyStringExtensionsGroup
{
public static string MethodOne(this Group1 group) => group.Source + "My Method One";
public static string MethodTwo(this Group2 group) => group.Source + "My Method Two";
public static Group1 Group1(this string source) => new Group1(source);
public static Group2 Group2(this string source) => new Group2(source);
}
Groups
public class Group1
{
public string Source { get; }
public Group1(string source) => Source = source;
}
public class Group2
{
public string Source { get; }
public Group2(string source) => Source = source;
}
Or you could just stuff your methods in the class, which is neater
public class Group1
{
public string Source { get; }
public Group1(string source) => Source = source;
public string MethodOne() => Source + "My Method One";
public string MethodTwo() => Source + "My Method Two";
}
public class Group2
{
public string Source { get; }
public Group2(string source) => Source = source;
public string MethodOne() => Source + "My Method One";
public string MethodTwo() => Source + "My Method Two";
}
Either way the usage is the same
Usage
var someString = "asd";
Console.WriteLine(someString.Group1().MethodOne());
Console.WriteLine(someString.Group2().MethodTwo());
Note : There are other ways and structures that can do this, however this will get you started if you want to go down this rabbit hole
In summary, I wouldn't do this at all :)
Upvotes: 1