I have an application where I have a method taking a PropertyInfo parameter and would like to call this method from IL. For similar methods taking a MethodInfo, for example, I can create an intermediate method taking a RuntimeMethodHandle and use GetMethodFromHandle. The IL can then use Ldtoken to pass the handle.
However, there does not appear to be an equivalent metadata token for properties. I can see why this might be the case (since properties are really just a way of bundling methods together and never 'called' from IL), but there is definitely property metadata associated with the type. I have access to this property metadata at Emit-time, so I'd like a way to be able to pass this directly without having to resort to Reflection by name at runtime (i.e. emit Reflection calls to GetProperty taking a string that will execute at runtime.) Is there a way to do this?
Per a request in the comments, here is the application:
I'm creating an adaptor class that exposes a property reference as its component bits via a bool this[int index] property. My application compiles PLC code to a .NET assembly and so I'm trying to create diagnostic accessors that approximate the easy bitwise access provided by the PLC (where you write MyTag.2 to indicate bit 2 of tag MyTag.) This syntax can't be used for consumption by C#, but PLC.GetBits().MyTag[2] is a reasonable approximation.
My original approach was implemented using PropertyInfo (which is how I encountered this issue), but I can certainly work around it by passing the applicable metadata from the PropertyInfo as multiple parameters. I was mainly just curious to see if it was possible to pass the PropertyInfo directly, since I hadn't ever run into this before.
No, I don't think you can. I say this in part through familiarity with that API, and in part because the Expression compiler in the C# compiler still uses reflection when it refers to a PropertyInfo, but uses more direct methods (ldtoken etc) when referring to types and methods (for example, a getter/setter). I suspect the C# compiler team would have used it if it existed.
However, in most common IL-emit scenarios, it is not necessary to pass around a PropertyInfo. options:
use MethodBase to get the getter or setter (methods can be fetched by token), and infer the property by name (not 100% robust, but should usually work)
pass around the name instead (ldstr)
Refer to Ecma-335, Partition I, 8.10.3 Property and event inheritance
Fundamentally, properties and events are constructs of the metadata intended for use by tools
that target the CLI and are not directly supported by the VES itself. Therefore, it is the job of the
source language compiler and the reflection library (see Partition IV – Kernel Package) to
determine rules for name hiding, inheritance, and so forth. The source compiler shall generate
CIL that directly accesses the methods named by the events and properties, not the events or
properties themselves.
Ecma-335, Partition I, 8.11.3 Property definitions
A property definition is always part of either an interface definition or a class definition. The
name and value of a property definition is scoped to the type that includes the property
definition. The CTS requires that the method contracts that comprise the property shall match the
method implementations, as with any other method contract. There are no CIL instructions
associated with properties, just metadata.
Related
Preamble:
I'm working on implementing a system where a developer can specify on object of type T which has N number of properties.
What I'm trying to accomplish:
I'd like to be able to provide more concrete control over how these properties are set and retrieved. This is difficult because of the limitless number of configurations possible.
Solutions I'm pursuing:
Is it possible to set getters dynamically?
Either through attributes? Generate the methods after the fact during construction like :
foreach(var property in typeOf(T).GetProperties())
{
//dynamically generate getter method which returns this property.
}
Possibly wrap type T in a container object which has the type as one of its properties. Then set up some type of special getter for that.
Why I want to do this:
Currently all the types for T get converted based on Typecode. Allowing people using this library to easily parse in values from various sources (databases, text files, app configs, etc.) as properties of type T. The point being to deliver these properties as type safe values rather than magic strings.
This is the impetus for wanting to use reflection for this but I could see numerous other applications for this I would imagine.
I could just say "Hey make all of your types nullable." so that it would be easy to determine which properties have been set in type T. I'd like to abstract away even that though.
The other option for this would be "Make sure you understand that certain types have default values. Be certain you're ready to accept those values, or set default values of your own (including making it nullable and setting it to null if so desired). Essentially trusting this to the developer rather than abstracting it. <==== This is what I'm currently doing.
Being able to dynamically generate methods, especially getters and setters, dynamically via reflection or a combination of reflection and C# Actions would be incredibly valuable. Any insight or ideas would be greatly welcome. Either ways of accomplishing the solutions I'm pursuiing or another idea which achieves the same ends.
I don't believe you can set accessor methods on properties of static types. Another challenge that I think you will have to deal with will be your goal to provide type safety - you see, if your types are built in run-time, compile-time checks will not work, which means you'll have to rely on dynamic a lot - this is slow. But not all is lost. You have at least two options:
The quick and dirty way
You can generate proxy classes that would inherit from your concrete types. Theese will give you ability to intercept method calls to base members and do pretty much anything you please. See Castle DynamicProxy
The hard but proper way (actually first option is using this behind the scenes)
You're looking at IL Generator namespace. This is a step above linq expression trees in a sense that you can generate your own assembly and types, all programmatically. This however is incredibly complex and error prone. I'd suggest you try option one first and only generate your own IL if you absolutely must.
UPD I know you didn't want magic strings, an I guess this is a bit less conventional solution, but also check out CSharpCodeProvider of CodeDOM namespace
Since Attributes are really just Metadata attached to assemblies, does that mean that Attribute Objects are only created on request (such as when you call GetCustomAttributes)?
Or are they created on creation of the object?
Or, a combination of the first 2, created when the object is created due to attribute scanning by the CLR?
From CLR via C#, third edition:
If you want to construct an attribute object, you must call either GetCustomAttributes or
GetCustomAttribute. Every time one of these methods is called, it constructs new instances
of the specified attribute type and sets each of the instance’s fields and properties based on the values specified in the source code. These methods return references to fully constructed instances of the applied attribute classes.
So yes, they are only created on request.
They are created on request.
For example, if you add some .NET 3.0 attributes to a .NET 2.0 Assembly (e.g. WCF DataContractAttribute), you'll still be able to use the .NET 2.0 Assembly on a machine that doesn't have .NET 3.0 installed, provided you don't have any code that attempts to access the attributes.
It is not quite that clean, attributes also affect code generation. Some attributes are interpreted by the compiler, [DllImport] for example. Some are discovered by the jitter, [MethodImpl] for example. This is infinitely extended to other tools and classes in the framework that were written to take advantage of attributes.
But these tools are just doing what you need to do if you want to find your own attributes, calling GetCustomAttributes() is required. That kind of code is never associated with an instance of the object, attributes apply to types.
Few days ago I asked what this attribute means:
[System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint="RtlZeroMemory")] public unsafe static extern bool ZeroMemory(byte* destination, int length);
I have learned that attributes are metadata but what I do not understand is - is this needed in this case? I thought metada are just that, metadata that can be ommited. Also the code seems to be running fine when I remove the attibute.
I would like to understand.
PS: Hans Passant mentioned its covered by any book about .NET Csharp..it is not, the largely used one VS 2010 from John Sharp does not cover it.
The metadata does usually have a reason and a meaning. In this particular case it tells the compiler how to bind this external method definition (e.g. to which DLL import it matches).
Other attributes control how interop is performed by the framework, yet other control how the object inspector displays data. 3rd-party attributes are also used extensively to control various behaviors, for instance for finding specific type information when performing reflection.
No, this attribute is absolutely required. It informs the CLR that what you've defined actually uses platform invokation services (or, P/Invoke) to call a function defined in unmanaged code.
Specifically, the RtlZeroMemory function, defined in the library kernel32.dll.
Without it, the compiler wouldn't know which function it was bound to, and the CLR wouldn't know which function to call at run-time.
This attribute is doing 2 things
Informs the CLR that the C method being invoked lives in kernel32.dll
Informs the CLR that the C method name is RtlZeroMemory and not ZeroMemory as it's named in code.
Yes this attribute is 100% necessary. It's a requirement for any PInvoke method to at the least name the DLL the C method lives in.
As your example shows, attributes are in fact needed in several key areas of .NET programming.
Attributes provide a model known as "Aspect-Oriented Programming" or AOP. Instead of having to write code that performs some specific task, such as serialization, DLL interop, logging, etc, you can instead simply decorate the classes or members on which you want these tasks performed with an attribute. Attributes are a special type of class, with members which can be invoked by the CLR as it runs your code, that will perform the task you wanted when you decorated the code.
You are correct in part; many attributes are intended simply to store metadata. DescriptionAttribute is a good one. However, even in this case, the attribute is important depending on how it's used. If you are decorating a member of a GUI class that you want to use in the designer, [Description()] provides valuable information to the user of the class in the designer, which may not be you. I've also seen and used many alternate uses for DescriptionAttribute; it can be applied to almost anything, so I've used it to provide "friendly names" for Enum constants, coupled with a GetDescription() extension method to grab them, when using Enums to populate drop-down lists.
So, while it's technically "metadata", an attribute's being "required" is governed by how much you want the task inherent in that attribute to be performed.
As for this particular attribute, I'm not too sure. To be honest, I've never seen it in almost a year of constant C#.
However, attributes in general can prove very useful. For instance, I was having issues with the VS2010 designer setting autocomplete properties in the wrong order, and getting run-time errors as a result. The solution was to add attributes to the autocomplete properties that prevented the designer from writing these properties to the design file, and instead setting the properties myself in the .cs file (in the proper order).
Summary: Attributes (usually) are not required, but can prove extremely useful.
I recently started work at a new company and a .net web application we have is built using reflection. I have only been out of school for a year and haven't worked with this concept. After studying the code... it looks like there is a single backend interface of type object that has about 20 classes that inherit from it. lots of generic gets and sets
On the surface it looks like standard inheritance to me. I guess my question is, what makes this reflection? Is it because the interface is not strongly typed?
Thanks
Please read about Reflection on Wikipedia first. Then check out the Reflection Namespace on MSDN.
I believe I know the general pattern that you are encountering. The need for reflection arises as the user can specify type and member names at runtime. The program then has to use reflection to map the supplied names to actual type members.
Generally speaking, if your program inspects object types at runtime, then you are using reflection.
BTW, Strong and Weak are attributes of the language type system, but not of any application or structure ( eg. interface, etc ) written using that language. ie. "C# is considered by many to be a strongly typed language".
Who says it is "built using reflection"? Your coworkers?
Generally speaking, to use reflection means to inspect or generate code at runtime.
If the application is using reflection, it is probably using stuff from the System.Reflection namespace, so to get a feel for the extent to which reflection is used, you could remove references to this namespace and see what breaks...
"Reflection: The ability to discover the composition of a type (e.g., class, interface, structure, enumeration, or delegate) at runtime."
I believe your coworkers are referring to how they instantiate your objects. I'm sure your objects are built using standard inheritance.
a) The application cant be buit using reflection. Reflection is most likely a part of the application. Just like inheritance in the case of one parent and 20 children classes as you mention.
b) Reflection is used to analyze an object at run time. Implying supposing you have an object referrence of the type object and maybe this object type could vary and you want at run time to see al the properties then reflection is used. Another case is when you have to call a method but you dont really know which method and its all general.
c) since its a .net app, in case of vb.net, a line with something like objectinstance.GetType.somemethod wil point to reflection. check it out
One definition of binding is that it is the act of replacing function names with memory addresses.
a) Thus I assume early binding means function calls are replaced with memory addresses during compilation process, while with late binding this replacement happens during runtime?
b) Why are virtual methods also considered early bound (thus the target method is found at compile time, and code is created that will call this method)? As far as I know, with virtual methods the call to actual method is resolved only during runtime and not compile time?!
thanx
EDIT:
1)
A a=new A();
a.M();
As far as I know, it is not known at compile time where on the heap (thus at which memory address ) will instance a be created during runtime.
Now, with early binding the function calls are replaced with memory addresses during compilation process. But how can compiler replace function call with memory address, if it doesn’t know where on the heap will object a be created during runtime ( here I’m assuming the address of method a.M will also be at same memory location as a )?
2)
v-table calls are neither early nor late bound. Instead there's an offset into a table of function pointers. The offset is fixed at compile time, but which table the function pointer is chosen from depends on the runtime type of the object (the object contains a hidden pointer to its v-table), so the final function address is found at runtime.
But assuming the object of type T is created via reflection ( thus app doesn’t even know of existence of type T ), then how can at compile time exist an entry point for that type of object?
Late Binding
With late binding all you have is the name of the method. At compile time you have no way of known if the method even exists. This is known as "duck typing" in languages such as Ruby or Python.
Late binding is slow because you have to look up the function by name. It is also dangerous because you are not protected from minor spelling errors.
Prior to version 4, C# has no support for late binding aside from explicitly calling the reflection API.
Early Binding
When using early binding you compile against an actual method. This method may be referred to directly or it may be a slot in a V-table. Either way you are garunteed to not throw a MissingMethod exception.
History
Visual Basic was well known for supporting both early and late binding, but due it its other limitations it was never considered a true dynamic language. At the same time, versions prior to 7 (a.k.a. VB.NET) had very poor support for enforcing early binding, making it hard to call it a static language either.
With .NET 4, both C# and VB can be said to offer most features expected of both static and dynamically typed languages.
At one point Java was mistakenly said to have late binding support when it fact it only had early bound, OOP style V-tables. This has caused quite a bit on confusion over the years.
Virtual methods are early bound when the compiler knows the exact type at compile time.
If the compiler does not have the exact type it will generate a vtable lookup style late binding instead.
A call to a virtual method may be early bound as Joshua explains (i.e. the compiler can see the exact type of the object, no polymorphism going on), or it may be made through a v-table.
C# only does late binding when you use reflection (and in the next version, there's a new "dynamic" keyword to request late binding).
v-table calls are neither early nor late bound. Instead there's an offset into a table of function pointers. The offset is fixed at compile time, but which table the function pointer is chosen from depends on the runtime type of the object (the object contains a hidden pointer to its v-table), so the final function address is found at runtime.
EDIT to address new questions:
In (1) the entire premise is false. Functions aren't stored anywhere near the objects that "own" them. In fact, there's only one copy of the function for the entire program, and the object instance is passed as a hidden "this" parameter so the function knows which instance is being addressed.
For (2), there are two possibilities. One, the function call is done through reflection via a MethodInfo or such. This is truly late-bound. Two, the function call is made through an interface or base class which the caller knows at compile-time, even though the total type of the object isn't known. In this case a v-table call is used because the layout of the v-table is determined by the base class or interface, so the caller knows it and can predetermine the offset into the v-table.