Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# monkey patching - is it possible?

Is it possible to write a C# assembly which when loaded will inject a method into a class from another assembly? If yes, will the injected method be available from languages using DLR, like IronPython?

namespace IronPython.Runtime
{
    public class Bytes : IList<byte>, ICodeFormattable, IExpressionSerializable
    {
        internal byte[] _bytes;

        //I WANT TO INJECT THIS METHOD
        public byte[] getbytes()
        {
            return _bytes;
        }
    }
}

I need that method, and I would like to avoid recompiling IronPython if possible.

like image 773
Meh Avatar asked May 22 '26 17:05

Meh


2 Answers

This can be done with frameworks such as TypeMock, which hook into the framework profiling APIs.

However this kind of injection is usually only used to facilitate unit testing rather than within production code and comes with a performance hit. My opinion is that if you are having to do something as drastic as this outside of unit testing, then do you are probably doing something wrong.

like image 51
TheCodeKing Avatar answered May 25 '26 05:05

TheCodeKing


It is possible to access extension methods from IronPython. See http://blogs.msdn.com/saveenr/archive/2008/11/14/consuming-extension-methods-in-ironpython.aspx

like image 29
Darrel Miller Avatar answered May 25 '26 05:05

Darrel Miller