Proposal: Add a way to extend existing classes #1852
Replies: 6 comments
-
I believe this would fall under the discussion here: #164 |
Beta Was this translation helpful? Give feedback.
-
Extension Methods? https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods |
Beta Was this translation helpful? Give feedback.
-
Existing extension methods can only be used on instances of existing classes, and not on a static type, so you can't just go Console c = new Console(); Since Console is a static class. I'm also proposing a more refined version, so even if the above were possible, you wouldn't need to create a new instance of it as you would be extending the base class itself. Think of it as a neater version of downloading Console.cs, adding a new method, then using the modified class instead of the original. |
Beta Was this translation helpful? Give feedback.
-
@Reelix so basically you want to add static methods to existing static classes? For your specific use case I would actually recommend to use dependency injection instead. This way you would always have a single set of instance methods to invoke while being free to swap out their implementation. Do yoy have another use case for your proposal? |
Beta Was this translation helpful? Give feedback.
-
C# 8 will have Extension Everything, where you can do extension static methods. |
Beta Was this translation helpful? Give feedback.
-
Extension Everything isn't slated for C# 8.0. It's bundled along with a number of future ideas like concepts, shapes and type classes which the team wants to explore over the coming months. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Say you have basic logging in your program, and in certain cases you want to write a console line as well. In this case, you have three viable options:
1.) Hook into the console, and log everything written to it
2.)
Console.WriteLine("Text Here");
Logger.Log("Text Here");
3.)
SomeFunc("Text Here");
void SomeFunc(string text)
{
Console.WriteLine(text);
Logger.Log(text);
}
I propose a way to be able to extend the base classes, and in doing so allow the developer to add additional functionality without the need to add new classes, so you can eventually add a new class to your project, and go like:
Console.LogLine("Text Here");
This could possibly be done by creating a class of a new class type "extension" that requires an existing class type as a name, and in doing so allows you to add new methods onto those classes.
Beta Was this translation helpful? Give feedback.
All reactions