Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monkey Patching in C#

Is it possible to extend or modify the code of a C# class at runtime?

My question specifically revolves around Monkey Patching / Duck Punching or Meta Object Programming (MOP), as it happens in scripting languages such as Groovy, Ruby etc.

like image 914
humblecoder Avatar asked Dec 27 '10 10:12

humblecoder


People also ask

What is monkey patching in code?

Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. A monkey patch (also spelled monkey-patch, MonkeyPatch) is a way to extend or modify the runtime code of dynamic languages (e.g. Smalltalk, JavaScript, Objective-C, Ruby, Perl, Python, Groovy, etc.)

What is monkey patching give example?

In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time. We use above module (monk) in below code and change behavior of func() at run-time by assigning different value.

How does monkey patching work?

Monkey patching is reopening the existing classes or methods in class at runtime and changing the behavior, which should be used cautiously, or you should use it only when you really need to. As Python is a dynamic programming language, Classes are mutable so you can reopen them and modify or even replace them.

What does monkey Patch_all () do?

The primary purpose of this module is to carefully patch, in place, portions of the standard library with gevent-friendly functions that behave in the same way as the original (at least as closely as possible). The primary interface to this is the patch_all() function, which performs all the available patches.


1 Answers

Is it possible to extend or modify the code of a C# class at run-time?

No it is not possible to do this in .NET. You could write derived classes and override methods (if they are virtual) but you cannot modify an existing class. Just imagine if what you were asking was possible: you could modify the behavior of some existing system classes like System.String.

You may also take a look at Extension methods to add functionality to an existing class.

like image 158
Darin Dimitrov Avatar answered Oct 11 '22 01:10

Darin Dimitrov