Creating a function dynamically at run-time - c#

It probably isn't even possible to do this, but I will ask anyway.
Is it possible to create a function that receives a string and then uses it as a right side argument for the goes to operator (=>) used in lambda?
Actually, what I want to do is to be able to redefine an specific method of a specific class during runtime. I want to be write down a function with the program running and attaching it to a delegate. Is it possible?

You have several ways how to do it:
dynamically create lambda expression (look at Dynamic LINQ: Part 1)
dynamically create CodeDom model and compile it at run-time (look at CodeDom.Compiler namespace
dynamically create C#/VB.NET source code and compile it at run-time (look at CSharpCodeProvider and VBCodeProvider classes )
dynamically create object model, which can do same things like the method (look at Strategy Design Pattern

The easiest way to do it is probably DLINQ as TcKs suggested.
The fastest (I believe, in 3.5) is to create a DynamicMethod. Its also the scariest method as well. You're essentially building a method using IL, which has about the same feel as writing code in machine language.
I needed to do this to dynamically attach event handlers in some thing or another (well, I didn't need to do it, I just wanted to make unit testing events easier). It seemed a bit daunting at the time because I don't know crap about IL, but I figured out a simple way to accomplish this.
What you do is create a method that does exactly what you want. The more compact the better. I'd provide an example if I could figure out exactly what you're trying to do. You write this method in a class within a DLL project and compile it in release mode. Then you open the DLL in Reflector and disassemble your method. Reflector gives you the option of what language you wish to disassemble to--select IL. You now have the exact calls you need to add to your dynamic method. Just follow the example on MSDN, switching out the example's IL for your reflected methods' code.
Dynamic methods, once constructed, invoke at about the same speed as compiled methods (saw a test where dynamic methods could be called in ~20ms where reflection took over 200ms).

Your question is pretty unclear, but you can certainly use expression trees to create delegates dynamically at execution time. (There are other ways of doing it such as CodeDOM, but expression trees are handier if they do all you need. There are significant restrictions to what you can do, however.)
It's often easier to use a lambda expression with some captured variables though.
For example, to create a function which will add the specified amount to any integer, you could write:
static Func<int, int> CreateAdder(int amountToAdd)
{
return x => x + amountToAdd;
}
...
var adder = CreateAdder(10);
Console.WriteLine(adder(5)); // Prints 15
If this doesn't help, please clarify your question.

Not that I am recommending this over the other better options, but there is a 7th method and thats to use AssemblyBuilder,ModuleBuilder,TypeBuilder, and MethodBuilder in the System.Reflection.Emit namespace to create a dynamic assembly. This is the same similar voodoo as using DynamicMethod.
For example you could use these to, at runtime, create a proxy class for a type and override virtual methods on that type.
To get you started here is some code...
using System;
using System.Reflection;
using System.Reflection.Emit;
var myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName("Test"), AssemblyBuilderAccess.RunAndSave);
var myModule = myAssembly.DefineDynamicModule("Test.dll");
var myType = myModule.DefineType("ProxyType", TypeAttributes.Public | TypeAttributes.Class,
typeof(TypeToSeverelyModifyInAnUglyWayButItsNecessary));
var myMethod = myType.DefineMethod("MethodNameToOverride",
MethodAttributes.HideBySig | MethodAttributes.Public,
typeof(void),Type.EmptyTypes);
var myIlGenerator = myMethod.GetILGenerator();
myIlGenerator.Emit(OpCodes.Ret);
var type = myType.CreateType();

Use .net core 3.1, you can create dynamic method with IL language(mono is same as well):
using System.Linq.Expressions;
using System.Reflection.Emit;
class Program
{
static void Main()
{
DynamicMethod hellomethod = new DynamicMethod("WriteLine", typeof(void), new[] { typeof(string) }, typeof(Program).Module);
ILGenerator il = hellomethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
il.Emit(OpCodes.Ret);
Action<string> hello4 = (Action<string>)hellomethod.CreateDelegate(typeof(Action<string>));
hello4("Hello World!");
}
}

If you declare the method as virtual, you might be able to use Castle's DynamicProxy to substitute a dynamically-generated (with one of the other answer's methods) implementation at runtime:
Castle DynamicProxy is a library for generating lightweight .NET proxies on the fly at runtime. Proxy objects allow calls to members of an object to be intercepted without modifying the code of the class. Both classes and interfaces can be proxied, however only virtual members can be intercepted.

The second paragraph in your question suggests that really what you might be after is straightforward IOC (Inversion of Control)
Instead of declaring an instance of your class, you declare an instance of an interface and based on whatever condition you choose, you use the particular overriding class with the correct method in it. Hope that makes sense.

You should check to see if your problem can be solved with simple polymorphism first. Unless you're defining abstract interoperability to another language or editing the compiler, trying to change a method at runtime is probably the wrong solution to the problem.

Related

C# Method-reference of constructor

In C# I can have references of methods and static methods. Can I also get the reference of a classes constructor?
In Java I can say Supplier<MyClass> createMyClass = MyClass::new (instead of the longer lambda syntax).
In C# I only know the notation Func<MyClass> createMyClass = () => MyClass(). But I think the Java way with the constructor reference is better readable.
And I don't want to make a static CreateMyClass function. I really want the constructor.
No, there's no equivalent of method group conversions for constructors, or properties, indexers or operators.
It's an entirely reasonable idea, but it isn't in C# at the moment. It is, however, tracked as part of a feature request in the C# design repo - so you may want to subscribe to that issue.

How can I implement my own type of extern?

In our product, we have things called "services" which are the basic means of communication between different parts of the product (and especially between languages—an in-house language, C, Python and .NET).
At present, code is like this (Services.Execute utilising params object[] args):
myString = (string)Services.Execute("service_name", arg1, arg2, ...);
I'd rather like to be able to write code like this and get the benefits of type checking and less verbose code:
myString = ServiceName(arg1, arg2, ...);
This can be achieved with a simple function,
public static string ServiceName(int arg1, Entity arg2, ...)
{
return (string)Services.Execute("service_name", arg1, arg2, ...);
}
But this is rather verbose, and not quite so easy to manage when doing it for scores of services, as I intend to be doing.
Seeing how extern and the DllImportAttribute work, I hope it should be possible to hook this up by some means like this:
[ServiceImport("service_name")]
public static extern string ServiceName(int arg1, Entity arg2, ...);
But I don't know how to achieve this at all and can't seem to find any documentation for it (extern seems to be a fairly vaguely defined matter). The closest I've found is a somewhat related question, How to provide custom implementation for extern methods in .NET? which didn't really answer my question and is somewhat different, anyway. The C# Language Specification (especially, in version 4.0, section 10.6.7, External methods) doesn't help.
So, I want to provide a custom implementation of external methods; can this be achieved? And if so, how?
The C# extern keyword does very little, it just tells the compiler that the method declaration won't have a body. The compiler does a minimum check, it insists that you provide an attribute as well, anything goes. So this sample code will compile just fine:
class Program {
static void Main(string[] args) {
foo();
}
class FooBar : Attribute { }
[FooBar]
static extern void foo();
}
But of course it will not run, the jitter throws its hands up at the declaration. Which is what is required to actually run this code, it is the jitter's job to generate proper executable code for this. What is required is that the jitter recognizes the attribute.
You can see this done in the source code for the jitter in the SSCLI20 distribution, clr/src/md/compiler/custattr.cpp source code file, RegMeta::_HandleKnownCustomAttribute() function. That's code that's accurate for .NET 2.0, I'm not aware of additions to it that affect method calling. You'll see it handling the following attributes that relate to code generation for method calls, the kind that will use the extern keyword:
[DllImport], you no doubt know it
[MethodImpl(MethodImplOptions.InternalCall)], an attribute that's used on methods that are implemented in the CLR instead of the framework. They are written in C++, the CLR has an internal table that links to the C++ function. A canonical example is the Math.Pow() method, I described the implementation details in this answer. The table is not otherwise extensible, it is hard-baked in the CLR source code
[ComImport], an attribute that marks an interface as implemented elsewhere, invariably in a COM server. You rarely program this attribute directly, you'd use the interop library that's generated by Tlbimp.exe instead. This attribute also requires the [Guid] attribute to give the required guid of the interface. This is otherwise similar to the [DllImport] attribute, it generates a pinvoke kind of call to unmanaged code but using COM calling conventions. This can of course only work properly if you actually have the required COM server on your machine, it is otherwise infinitely extensible.
A bunch more attributes are recognized in this function but they don't otherwise relate to calling code that's defined elsewhere.
So unless you write your own jitter, using extern isn't a viable way to get what you want. You could consider the Mono project if you want to pursue this anyway.
Common extensibility solutions that are pure managed are the largely forgotten System.AddIn namespace, the very popular MEF framework and AOP solutions like Postsharp.
I needed to do something quite similar (relaying method calls) recently. I ended up generating a type that forwarded method calls dynamically during runtime.
For your use case, the implementation would look something like this. First create an interface that describes your service. You will use this interface wherever you want to call the service in your code.
public interface IMyService
{
[ServiceImport("service_name")]
string ServiceName(int arg1, string arg2);
}
Then run the code to generate a class that implements this interface dynamically.
// Get handle to the method that is going to be called.
MethodInfo executeMethod = typeof(Services).GetMethod("Execute");
// Create assembly, module and a type (class) in it.
AssemblyName assemblyName = new AssemblyName("MyAssembly");
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run, (IEnumerable<CustomAttributeBuilder>)null);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule");
TypeBuilder typeBuilder = moduleBuilder.DefineType("MyClass", TypeAttributes.Class | TypeAttributes.Public, typeof(object), new Type[] { typeof(IMyService) });
typeBuilder.DefineDefaultConstructor(MethodAttributes.Public);
// Implement each interface method.
foreach (MethodInfo method in typeof(IMyService).GetMethods())
{
ServiceImportAttribute attr = method
.GetCustomAttributes(typeof(ServiceImportAttribute), false)
.Cast<ServiceImportAttribute>()
.SingleOrDefault();
var parameters = method.GetParameters();
if (attr == null)
{
throw new ArgumentException(string.Format("Method {0} on interface IMyService does not define ServiceImport attribute."));
}
else
{
// There is ServiceImport attribute defined on the method.
// Implement the method.
MethodBuilder methodBuilder = typeBuilder.DefineMethod(
method.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
CallingConventions.HasThis,
method.ReturnType,
parameters.Select(p => p.ParameterType).ToArray());
// Generate the method body.
ILGenerator methodGenerator = methodBuilder.GetILGenerator();
LocalBuilder paramsLocal = methodGenerator.DeclareLocal(typeof(object[])); // Create the local variable for the params array.
methodGenerator.Emit(OpCodes.Ldc_I4, parameters.Length); // Amount of elements in the params array.
methodGenerator.Emit(OpCodes.Newarr, typeof(object)); // Create the new array.
methodGenerator.Emit(OpCodes.Stloc, paramsLocal); // Store the array in the local variable.
// Copy method parameters to the params array.
for (int i = 0; i < parameters.Length; i++)
{
methodGenerator.Emit(OpCodes.Ldloc, paramsLocal); // Load the params local variable.
methodGenerator.Emit(OpCodes.Ldc_I4, i); // Value will be saved in the index i.
methodGenerator.Emit(OpCodes.Ldarg, (short)(i + 1)); // Load value of the (i + 1) parameter. Note that parameter with index 0 is skipped, because it is "this".
if (parameters[i].ParameterType.IsValueType)
{
methodGenerator.Emit(OpCodes.Box, parameters[i].ParameterType); // If the parameter is of value type, it needs to be boxed, otherwise it cannot be put into object[] array.
}
methodGenerator.Emit(OpCodes.Stelem, typeof(object)); // Set element in the array.
}
// Call the method.
methodGenerator.Emit(OpCodes.Ldstr, attr.Name); // Load name of the service to execute.
methodGenerator.Emit(OpCodes.Ldloc, paramsLocal); // Load the params array.
methodGenerator.Emit(OpCodes.Call, executeMethod); // Invoke the "Execute" method.
methodGenerator.Emit(OpCodes.Ret); // Return the returned value.
}
}
Type generatedType = typeBuilder.CreateType();
// Create an instance of the type and test it.
IMyService service = (IMyService)generatedType.GetConstructor(new Type[] { }).Invoke(new object[] { });
service.ServiceName(1, "aaa");
This solution is probably a bit messy, but if you want to save having to create the code yourself, it works quite well.
Note that there is a performance hit associated with creating the dynamic type. However this is usually done during initialization and should not affect runtime too much.
Alternatively I advise you take a look at PostSharp that allows you to generate code during compile time. It is a paid commercial solution however.
Even though it's not quite what you asked for, I would recommend creating your own T4 template which will generate these helper methods. This is especially useful if you have some programmatic API to get a list of service names and it's applicable parameter types.

Why not a memberinfo() reflection function for C# [duplicate]

This question already has answers here:
Why is there not a `fieldof` or `methodof` operator in C#? [closed]
(4 answers)
Closed 9 years ago.
There is sizeof() and typeof(), but why not a memberinfo() returning an instance of System.Reflection.MemberInfo for the part of code selected in order to aid in reflection code.
Example:
Program()
{
Type t = typeof(Foo);
Foo foo = new Foo();
PropertyInfo pi = memberinfo(Foo.Name) as PropertyInfo;
// or shall it be like this
// PropertyInfo pi = memberinfo(foo.Name) as PropertyInfo;
string name = pi.GetValue(foo, null);
}
I am trying to understand if there is a fundamental reason why this could be implemented in the C# spec.
I am not bashing anything, I am just doing some wishful thinking, so be kind please.
Eric Lippert talks about this extensively on his blog
To quote directly from that post:
Just off the top of my head, here are a few {reasons why this hasn't been done}. (1) How do you unambiguously specify that you want a method info of an specific explicit interface implementation? (2) What if overload resolution would have skipped a particular method because it is not accessible? It is legal to get method infos of methods that are not accessible; metadata is always public even if it describes private details. Should we make it impossible to get private metadata, making the feature weak, or should we make it possible, and make infoof use a subtly different overload resolution algorithm than the rest of C#? (3) How do you specify that you want the info of, say, an indexer setter, or a property getter, or an event handler adder?
There are a couple of items which make this type of feature difficult. One of the primary ones being overloaded methods.
class Example {
public void Method() {}
public void Method(int p1) {}
}
Which MethodInfo would the following return?
var info = memberinfo(Example.Method);
As Wesley has pointed out though, Eric Lippert's Blog has the full discussion on this issue.
There are numerous reasons why compile-time member reflection has not yet been implemented in C# - but most of them basically boil down to opportunity cost - there are many other languages features and enhancements that offer more benefit to more users. There's also the consideration that an infoof syntax could be complicated, confusing, and ultimately less powerful than using string-based reflection. It also wouldn't be a complete replacement for reflection since in many instances the metadata being manipulated isn't known at compile time.
However, all is not lost, there are a number of tricks that you can employ to perform slightly safer reflection that leverages capabilities of the C# language. For instance, we can take advantage of lambda expressions and expression trees to extract MemberInfo information. A simple example is:
public static class MethodExt {
static MethodInfo MemberInfo(Action d) {
return d.Method;
}
// other overloads ...
}
which works when you pass in a (non-anonymous) action delegate:
MethodInfo mi = MethodExt.MemberInfo( Object.ToString );
An implementation of the above using expression trees can more robust and flexible, but also substantially more complicated. It could be used to represent member and property access, indexers, etc.
The main issue with all such "fancy" approaches, is that they are confusing to developers who are used to seeing traditional reflection code. They also can't handle all cases, which often results in an unfortunate mixture of traditional reflection code and fancy expression tree code. Personally, while such techniques are interesting and inventive, it's probably best to avoid it in production code.
I myself use an approach that reads the IL from an anonymous method (using Mono.Reflection namespace) and grabs the info of the last token found in the anonymous method. This tends to be the only way to get information about things like the add_EventHandler or set_Property or captured local variables. To actual get properties I use expression trees.
The syntax that I use is Reflect.Member<T>.InfoOf<TMember>(Func<T,TMember> memberfunc) where Member is replaced with the type I'm interested in. It's verbose sure, but it lets a user know exactly what the code is trying to do. I also have Reflect.Member styles for things like statics and constructors.
Here is the relevant code snippet::
internal static MemberInfo GetLastMemberOfType(MethodBase method, MemberTypes memberType)
{
var instructions = method.GetInstructions();
var operandtype = memberType == MemberTypes.Field ? OperandType.InlineField : OperandType.InlineMethod;
for (int i = instructions.Count-1; i > -1 ; i--)
{
if (instructions[i].OpCode.OperandType == operandtype)
{
return instructions[i].Operand as MemberInfo;
}
}
return null;
}
Does it replace string based reflection? Absolutely not. Does it make my code safer while I'm refactoring interfaces and what not? Absolutely.
Will it ship with the product I'm working on? Probably not.

When should one use dynamic keyword in c# 4.0?

When should one use dynamic keyword in c# 4.0?.......Any good example with dynamic keyword in c# 4.0 that explains its usage....
Dynamic should be used only when not using it is painful. Like in MS Office libraries. In all other cases it should be avoided as compile type checking is beneficial. Following are the good situation of using dynamic.
Calling javascript method from Silverlight.
COM interop.
Maybe reading Xml, Json without creating custom classes.
How about this? Something I've been looking for and was wondering why it was so hard to do without 'dynamic'.
interface ISomeData {}
class SomeActualData : ISomeData {}
class SomeOtherData : ISomeData {}
interface ISomeInterface
{
void DoSomething(ISomeData data);
}
class SomeImplementation : ISomeInterface
{
public void DoSomething(ISomeData data)
{
dynamic specificData = data;
HandleThis( specificData );
}
private void HandleThis(SomeActualData data)
{ /* ... */ }
private void HandleThis(SomeOtherData data)
{ /* ... */ }
}
You just have to maybe catch for the Runtime exception and handle how you want if you do not have an overloaded method that takes the concrete type.
Equivalent of not using dynamic will be:
public void DoSomething(ISomeData data)
{
if(data is SomeActualData)
HandleThis( (SomeActualData) data);
else if(data is SomeOtherData)
HandleThis( (SomeOtherData) data);
...
else
throw new SomeRuntimeException();
}
As described in here dynamics can make poorly-designed external libraries easier to use: Microsoft provides the example of the Microsoft.Office.Interop.Excel assembly.
And With dynamic, you can avoid a lot of annoying, explicit casting when using this assembly.
Also, In opposition to #user2415376 ,It is definitely not a way to handle Interfaces since we already have Polymorphism implemented from the beginning days of the language!
You can use
ISomeData specificData = data;
instead of
dynamic specificData = data;
Plus it will make sure that you do not pass a wrong type of data object instead.
Check this blog post which talks about dynamic keywords in c#. Here is the gist:
The dynamic keyword is powerful indeed, it is irreplaceable when used with dynamic languages but can also be used for tricky situations while designing code where a statically typed object simply will not do.
Consider the drawbacks:
There is no compile-time type checking, this means that unless you have 100% confidence in your unit tests (cough) you are running a risk.
The dynamic keyword uses more CPU cycles than your old fashioned statically typed code due to the additional runtime overhead, if performance is important to your project (it normally is) don’t use dynamic.
Common mistakes include returning anonymous types wrapped in the dynamic keyword in public methods. Anonymous types are specific to an assembly, returning them across assembly (via the public methods) will throw an error, even though simple testing will catch this, you now have a public method which you can use only from specific places and that’s just bad design.
It’s a slippery slope, inexperienced developers itching to write something new and trying their best to avoid more classes (this is not necessarily limited to the inexperienced) will start using dynamic more and more if they see it in code, usually I would do a code analysis check for dynamic / add it in code review.
Here is a recent case in which using dynamic was a straightforward solution. This is essentially 'duck typing' in a COM interop scenario.
I had ported some code from VB6 into C#. This ported code still needed to call other methods on VB6 objects via COM interop.
The classes needing to be called looked like this:
class A
{
void Foo() {...}
}
class B
{
void Foo() {...}
}
(i.e., this would be the way the VB6 classes looked in C# via COM interop.
Since A and B are independent of each other you can't cast one to the other, and they have no common base class (COM doesn't support that AFAIK and VB6 certainly didn't. And they did not implement a common interface - see below).
The original VB6 code which was ported did this:
' Obj must be either an A or a B
Sub Bar(Obj As Object)
Call Obj.Foo()
End Sub
Now in VB6 you can pass things around as Object and the runtime will figure out if those objects have method Foo() or not. But in C# a literal translation would be:
// Obj must be either an A or a B
void Bar(object Obj)
{
Obj.Foo();
}
Which will NOT work. It won't compile because object does not have a method called "Foo", and C# being typesafe won't allow this.
So the simple "fix" was to use dynamic, like this:
// Obj must be either an A or a B
void Bar(dynamic Obj)
{
Obj.Foo();
}
This defers type safety until runtime, but assuming you've done it right works just fine.
I wouldn't endorse this for new code, but in this situation (which I think is not uncommon judging from other answers here) it was valuable.
Alternatives considered:
Using reflection to call Foo(). Probably would work, but more effort and less readable.
Modifying the VB6 library wasn't on the table here, but maybe there could be an approach to define A and B in terms of a common interface, which VB6 and COM would support. But using dynamic was much easier.
Note: This probably will turn out to be a temporary solution. Eventually if the remaining VB6 code is ported over then a proper class structure can be used.
I will like to copy an excerpt from the code project post, which define that :
Why use dynamic?
In the statically typed world, dynamic gives developers a lot of rope
to hang themselves with. When dealing with objects whose types can be
known at compile time, you should avoid the dynamic keyword at all
costs. Earlier, I said that my initial reaction was negative, so what
changed my mind? To quote Margret Attwood, context is all. When
statically typing, dynamic doesn't make a stitch of sense. If you are
dealing with an unknown or dynamic type, it is often necessary to
communicate with it through Reflection. Reflective code is not easy to
read, and has all the pitfalls of the dynamic type above. In this
context, dynamic makes a lot of sense.[More]
While Some of the characteristics of Dynamic keyword are:
Dynamically typed - This means the type of variable declared is
decided by the compiler at runtime time.
No need to initialize at the time of declaration.
e.g.,
dynamic str;
str=”I am a string”; //Works fine and compiles
str=2; //Works fine and compiles
Errors are caught at runtime
Intellisense is not available since the type and its related methods and properties can be known at run time only. [https://www.codeproject.com/Tips/460614/Difference-between-var-and-dynamic-in-Csharp]
It is definitely a bad idea to use dynamic in all cases where it can be used. This is because your programs will lose the benefits of compile-time checking and they will also be much slower.

access private method in a different assembly c#

This may be a daft question as I can see the security reason for it to happen the way it does...
I have a licensing c# project, this has a class which has a method which generates my license keys. I have made this method private as I do not want anybody else to be able to call my method for obvious reasons
The next thing I want to do is to have my user interface, which is in another c# project which is referencing the licensing dll to be the only other 'thing' which can access this method outside of itself, is this possible or do i need to move it into the same project so that it all compiles to the same dll and I can access its members?
LicensingProject
-LicensingClass
--Private MethodX (GeneratesLicenseKeys)
LicensingProject.UI
-LicensingUiClass
--I want to be able to be the only class to be able to access MethodX
There is a reason why the license Key Generator is not just in the UI, that is because the licensing works by generating a hash on itself and compares it to the one generated by the License Generator.
I would prefer not to all compile to the dll as my end users do not need the UI code.
I know that by common sense a private method, is just that. I am stumped.
You could make it an internal method, and use InternalsVisibleToAttribute to give LicensingProject.UI extra access to LicensingProject.
Merhdad's point about enforcement is right and wrong at the same time. If you don't have ReflectionPermission, the CLR will stop you from calling things you shouldn't - but if you're using reflection from a fully trusted assembly, you can call anything. You should assume that a potential hacker is able to run a fully trusted assembly on his own machine :)
None of this will stop someone from using Reflector to decompile your code. In other words, making it private isn't really adding a significant amount of security to your licensing scheme. If anyone actually puts any effort into breaking it, they'll probably be able to.
This is really a comment, in response to Mehrdad's point about the runtime not performing access checks; here, you can see the JIT (it transpires) performing the access check - not reflection, and not the C# compiler.
To fix the code, make Foo.Bar public. Interestingly, it also verifies that Foo is accessible - so make Foo internal to see more fireworks:
using System;
using System.Reflection;
using System.Reflection.Emit;
static class Program {
static void Main() {
MethodInfo bar = typeof(Foo).GetMethod("Bar",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var method = new DynamicMethod("FooBar", null, new[] {typeof(Foo)});
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.EmitCall(OpCodes.Callvirt, bar, null);
il.Emit(OpCodes.Ret);
Action<Foo> action = (Action<Foo>) method.CreateDelegate(typeof(Action<Foo>));
Foo foo = new Foo();
Console.WriteLine("Created method etc");
action(foo); // MethodAccessException
}
}
public class Foo {
private void Bar() {
Console.WriteLine("hi");
}
}
public, private, ... stuff are just enforced by the compiler. You can use reflection to access them pretty easily (assuming the code has required permissions, which is a reasonable assumption as he has complete control on the machine). Don't rely on that assuming nobody can call it.
Foo.Bar may stay private...
To fix the code above, add one parameter at end of DynamicMethod constructor:
var method = new DynamicMethod("FooBar", null, new[] {typeof(Foo)}, true);
Add true to skip JIT visibility checks on types and members accessed by the MSIL of the dynamic method.

Categories

Resources