C
C#β€’2y ago
Dusty

βœ… Modify/prepend method implementation on build

Hey I was wondering if it is possible to modify a methods implementation. My first guess were source generators but they can only add code. So for example this
[ModifyImpl]
void DoStuff(string text)
{
Console.WriteLine(text);
}
[ModifyImpl]
void DoStuff(string text)
{
Console.WriteLine(text);
}
would be turned into
void DoStuff(string text)
{
// Some custom implementation before the users implementation e.g. an if clause

if (string.IsEmptyOrNull(text)
return;

Console.WriteLine(text);
}
void DoStuff(string text)
{
// Some custom implementation before the users implementation e.g. an if clause

if (string.IsEmptyOrNull(text)
return;

Console.WriteLine(text);
}
Any ideas?
4 Replies
ero
eroβ€’2y ago
class Base
{
virtual void M() { }
}

class Impl : Base
{
override void M()
{
base.M();
}
}
class Base
{
virtual void M() { }
}

class Impl : Base
{
override void M()
{
base.M();
}
}
Anton
Antonβ€’2y ago
there is no direct equivalent to python-like decorators there are partial methods for code generation, and there are delegates which you could take as a parameter but other than that, you'll have to model something custom with classes and the decorator pattern there are tools that can inject code into compiled dlls also what was it called... Rudy... Ruby... or something like that, I forgot the name but it's not common practice for many reasons
Anton
Antonβ€’2y ago
GitHub
GitHub - Fody/Fody: Extensible tool for weaving .net assemblies
Extensible tool for weaving .net assemblies. Contribute to Fody/Fody development by creating an account on GitHub.
Dusty
Dustyβ€’2y ago
πŸ˜‚ Technically this works yea, but the prepend logic should be in parent class. Apart from that i can't add dynamically checks/modification Thanks! Through Fody I found PostSharp (which is a bit cleaner imo) and that's exactly what I was looking forπŸ‘Œ