Make new object with reflection? - c#

I'm not sure if this is possible and after lengthy research I haven't found something conclusive.
I am trying to dynamically create a new object (itself a new Type) from a dictionary. So say I have key and value that key and value will become a property that returns the value. Something that I can use like this:
Sample code
public T getObject(Dictionary<string, string> myDict)
{
// make a new object type with the keys and values of the dictionary.
// sample values in dictionary:
// id : 112345
// name: "greg"
// gender: "m"
// Eventually also make the interface?
}
// Somewhere else:
var myNewObject = helper.getObject();
// what is expected here is that when I type myNewObject.
// I get id, name, gender as suggestions
int id = myNewObject.Id;
What is important for me is to get intellisense out of it. So I can type object. and suggestions with all the keys will come out. This way I don't need to know the dictionary in advance in order to access the values (or else I would simply use the dictionary).
I have looked into Clay but it isn't clear to me how to use it to get intellisense as I want it. I also found this post about it.
Additionally I checked ImpromptuInterface but for both the documentation is poor or I can't figure it out.
If this is possible with Clay (it sure seems like it) how could I do it so It can work as a library on other projects that won't reference Clay?
If something is unclear or this is a duplicate don't hesitate to comment.

To allow IntelliSense to work, the resulting type must be known at compile-time. So at the time you're working with object, you must know its concrete type (or, at least, a type or interface as concrete as you need - having all the methods and properties you want to access).
It's hard to see what you're actually trying to do, but if you do know the type at compile-time, you can make your helper method generic:
public T GetObject<T>(Dictionary<...> dictionary)
This allows you to specify the type you're expecting at the call site:
var obj = GetObject<SomeType>(dictionary);
If this does not sound reasonable to you, you could also use an explicit cast:
var obj = (SomeType)helper.getObject();
If you don't know the concrete type, you'll at least need to have a common interface (or a base class) you can use. The runtime generated type would then be created to implement this interface. But you'll only ever be able to access the members that are known at compile time. How would the compiler know all the possible keys that could exist in your dictionary at runtime? You're trying to code against some kind of contract - so formalize that contract in an interface (for example), and make the runtime generated type implement this interface.

Related

Delegating access to a class property instead of an object property

I've been trying to figure out a way to deal with property mapping and naming programmatically. The thing is that I don't want to have to change multiple portions of code to be able to extend the map. The code I have right now is like this:
public static class Names
{
public const string Property = "propertyNameToBeUsedInJson";
}
...
switch(propertyName)
{
case Property:
user.propertyToBeMapped = json.propertyValue;
break;
}
What I really wanted was to be able to have some sort of dictionary where I could do something like:
Dictionary<string, Action>() { {"propertyNameToBeUsedInJson", <Class of User>.propertyToBeMapped} };
That means I would be delegating access to a property of a Class, not to a concrete object. This way I can iterate over this dictionary and if it contains the key I'm looking for, then I just go and change the property pointed by the value.
I think that a overhead during initialization is ok, but I don't want to use Reflection on a per call basis.
The questions is: Is it possible to use the second way having in mind the statement above? If so, how should I go for it?
Just to summarize the comments:
It is definitely possible to do it with a dictionary, but properties cannot be used quite this way. Remember that properties are just syntactic sugar so you don't have to write get/set methods yourself. The best way to get it into a dictionary is probably by wrapping it into a delegate:
new Dictionary<string, Func<YourClass, string>>()
{
{"propertyNameToBeUsedInJson",
instance => instance.YourProperty}
};
Then, you would use it very easily like this (error checking omitted):
user.propertyToBeMapped = dictionary[propertyName](yourClassInstance);
This will only work if the instance is always the same class. If not, the first parameter of the Func would have to be some base class (maybe even object) and then the delegate would have to do some type-checking and conversion.

Properly using of the <T> type in generic methods in C#

So my real method is a lot different but I come down to this. It seems I don't fully understand how to handle the generic <T> type when I'm working with generic methods. My understanding is that we use generic methods when we want the same logic to work for different types, but we want the freedom to determine the exact type at run time. So it seems pretty natural to me that when I have a method like this :
internal static void ChangeCode<T>(Entity entity) where T : Entity
{
T tempEntity;
if (entity.GetType() == typeof(SomeMoreSpecificEntity))
{
tempEntity = new SomeMoreSpecificEntity();
}
}
However if I try something like this I get an error Can not convert type T to SomeMoreSpecificEntity.
So where am I wrong. Isn't the idea to be able to do exactly this - declare a common type in compile time and cast to more specific type in run time?
You can't do that. Check following situation:
You have another class named SomeMoreSpecificEntity2 which is declared:
class SomeMoreSpecificEntity2 : Entity
{
}
You call your method ChangeCode<SomeMoreSpecificEntity2>, so T is SomeMoreSpecificEntity2, so tempEntity is SomeMoreSpecificEntity2 as well, but you're trying to assign SomeMoreSpecificEntity to it. That can't work.
You can try changing it to :
internal static void ChangeCode<T>(Entity entity) where T : Entity
{
Entity tempEntity;
if (entity.GetType() == typeof(SomeMoreSpecificEntity))
{
tempEntity = new SomeMoreSpecificEntity();
}
}
It compiles.
No, the code you're trying to write is broken. For example, suppose I called:
ChangeCode<BananaEntity>(new SomeMoreSpecificEntity());
That would try to assign a reference of type SomeMoreSpecificEntity to a variable of type T, where T is BananaEntity.
It's not clear what you're trying to achieve, but that's why your current code won't compile. Given that you're not actually using T other than for a purpose for which it won't work your current code could be changed to make it a non-generic method, and just declare tempEntity as type Entity. Of course, that might not work for what you really want to do, but as you've only provided the non-working code, that's hard to determine :(
Three points about this line:
if (entity.GetType() == typeof(SomeMoreSpecificEntity))
Did you actually mean entity to be of type T rather than type Entity? Currently it can be any entity
Did you really want to check the exact type? Normally you'd use is instead of calling GetType and comparing it directly with a type
Normally comparing types like this is a sign that you should consider a redesign. It's definitely not generic at this point, as it only copes with types that are hard-coded in it.
tempEntity = (T)(object)new SomeMoreSpecificEntity();
T can only cast with object

Dynamic Generic declaration of type T

I have an array which stores a dictionary of Types:
//The dictionary:
Dictionary<CacheKey,Type> TypeLookup;
//This is the enum:
public enum CacheKey
{
UserProfile,
CustomerQuickSearch,
CommissionConfiguration
}
I would like to use this Dictionary to declare a variable of type T
//instead of
T myvar;
//I want to dynamically declare myvar as:
//1)get the type for the cacheKey from the dictionary:
Type type = TypeLookup[cacheKey];
//2)declare myvar as the corresponding Type:
type myvar;
The background is that I am building a Distributed Caching infrastructure. I have a great little CachingProvider that allows you to update an item in the cache.
I would like to expose this method as a webservice so that all the servers in my farm can have their cache updated. But I would like to have only one method exposed as a webservice which then updates the corresponding item in cache.
This is the method I'm trying to expose:
public static void UpdateCacheEntryItem<T>(CacheKey cacheKey, int id)
{
//look up the cacheEntry in cache which is a dictionary.
Dictionary<int, T> cacheEntry = (Dictionary<int, T>) CacheRef[cacheKey.ToString()];
//call the corresponding method which knows how to hydrate that item and pass in the id.
cacheEntry[id] = (T)HydrateCacheEntryItemMethods[cacheKey].Invoke(id);
}
Things I've tried:
1) I tried exposing the method directly as a WCF service but of course that doesn't work because of the on the method.
2) I tried casting the Dictionary which would be find because I don't need to do anthing with the return value, I just need to update the item in cache. But that didn't work either. Error that I get: Unable to cast object of type 'System.Collections.Generic.Dictionary2[System.Int32,CachingPrototype.CustomerQuickSearch]' to type 'System.Collections.Generic.Dictionary2[System.Int32,System.Object]'.
Your comments were very helpful and helped me to answer my question. The solution I came up with is to simply wrap my WCF service method in a switch statement so that I could call the UpdateCacheEntryItem method with the correct type of T. Since there is no way to convert from Type to the generic T operator, this is the only option. Since I don't have that many types in Cache, this works pretty well. (The other solution would be to use an interface as stated below but that would not be as strongly typed as I would like.)
[OperationContract]
public void UpdateCacheEntryItem(CacheKey cacheKey, int id)
{
switch (cacheKey)
{
case CacheKey.UserProfile:
CacheProvider.UpdateCacheEntryItem<UserProfile>(cacheKey, id);
break;
case CacheKey.CommissionConfig:
CacheProvider.UpdateCacheEntryItem<CommissionConfig>(cacheKey, id);
break;
case CacheKey.CustomerQuickSearch:
CacheProvider.UpdateCacheEntryItem<CustomerQuickSearch>(cacheKey, id);
break;
default:
throw new Exception("Invalid CacheKey");
}
Thanks everyone for your help, you are brilliant!
The idea of "dynamically declaring a variable" is contrary to the whole point of there being a type as part of the declaration of a variable. The idea is that you can tell the compiler the type, so that it can check what you're doing. In this case you haven't expressed any information about the type at all. You might as well just declare myVar as being of type object; that's basically the same as saying "I know pretty much nothing about the value of myVar, except that it's a reference."
If you've got a common interface of course, that would be great - and then you could use the members of that interface safely (after creating/fetching an appropriate instance, of course). But otherwise, there's really not a lot you can do unless you know something about the type at compile time.
In C# 4 you could declare the variable to be of type dynamic which would make all the binding dynamic - basically you can do pretty much what you like with it, and it will all be resolved at execution time. I'd advise using static typing wherever you can though, so that errors can be caught at compile time instead.
It looks to me that an interface and some casting will solve your problem. Just have each of your cacheable classes implement an interface. Store items of this type in your dictionary. Presumably, CacheRef would be of type Dictionary<CacheKey,Dictionary<CacheKey,ICacheable>>. All that is left is to make sure that your cacheable classes implement the interface.
public interface ICacheable
{
}
public static void UpdateCacheEntryItem(CacheKey cacheKey, int id)
{
//look up the cacheEntry in cache which is a dictionary.
Dictionary<CacheKey,ICacheable> cacheEntry = CacheRef[cacheKey.ToString()];
//call the corresponding method which knows how to hydrate that item and pass in the id.
cacheEntry[id] = (ICacheable)HydrateCacheEntryItemMethods[cacheKey].Invoke(id);
}
Note that this isn't, like #Jon Skeet says in his comments to his answer, enforcing the type in your Dictionary. It's up to your code to make sure that you are putting the right kind of objects into each cache. I'd be comfortable with this as long as your hydration methods were covered by unit tests to ensure that when given a particular key, they always produce objects of the appropriate type.

What is the best way to resolve an object?

I've written a resolver so I can have a very primitive DI framework. In the framework I allow for a dependency resolver to specify what default types to load if nothing is specified or registered.
However, the way I do the default loading has got me wondering. I'm not sure I'm doing it the best way it could be done.
Example:
T LoadDefaultForType<T>()
{
T _result = default(T);
if (typeof(T) == typeof(ISomeThing)
{
result = new SomeThing();
}
... more of the same
else
{
throw new NotSupportException("Give me something I can work with!");
}
return _result;
}
Update
The use of this would be to get the default object for a given interface in the event that a module or assembly has not configured the interface with a concrete type.
So for instance:
IoC.Resolve<ISomeThing>();
would need to return back to me a SomeThing object if nothing else has been registered to ISomeThing. The LoadDefaultForType in this case is kind of a last ditch effort to use a default (in this case whatever my domain model is).
The Resolve might shed some light on this as well:
T Resolve<T>()
{
T _result = default(T);
if (ContainedObjects.ContainsKey(typeof(T))
_result = (T)ContainedObjects[typeof(T)];
else
_result = LoadDefaultForType<T>();
return _result;
}
Any thoughts? Is there a better way to load default types given that I'm trying to allow for a Convention Over Configuration approach?
A few of suggestions:
You could create an attribute that can be used to mark the default implementation type of a particular interface. When you attempt to resolve the type, you could search for this attribute on T and use reflection to dynamically instantiate the type.
Alternatively, you could use reflection to search the available (loaded) assemblies or a concrete type that implements the interface. This can be a slow and expensive processes, so it would only make sense if the default case is rare.
Finally, if you're comfortable with naming conventions, you could search for a class that has the same name as the interface but without the leading "I". Not the best approach, but certainly one that can be made to work in a pinch.
public T LoadDefaultForType<T>()
where T : new()
{
T _result = new T();
return _result;
}
the code above would be a better way, but im not sure what it is your're trying todo, more information would help give u a better way of doing whatever it is you're trying to achieve.
I suggest taking a look at Unity for dynamically loading types, ie. Dependency injection
Neil's approach is the best if T can be resolved (I think it also has to be in the same assembly?).
Within your class, you could create an internal "registry" of sorts that could be used with System.Reflection to instantiate items without the giant switch statement. This preserves your "convention over configuration" while also keeping you DRY.
Edit
Combined with one aspect of LBushkin's answer to show some working code. (At least, it compiles in my head, and is taken from an example that I know works...)
public T LoadDefaultForType<T>()
{
try
{
string interfaceName = typeof(T).AssemblyQualifiedName;
// Assumes that class has same name as interface, without leading I, and
// is in ..."Classes" namespace instead of ..."Interfaces"
string className = interfaceName.Replace("Interfaces.I", "Classes.");
Type t = Type.GetType(className, true, true);
System.Reflection.ConstructorInfo info = t.GetConstructor(Type.EmptyTypes);
return (T)(info.Invoke(null));
}
catch
{
throw new NotSupportException("Give me something I can work with!");
}
}
Note that - as written - it won't work across assembly boundaries. It can be done using essentially the same code, however - you just need to supply the assembly-qualified name to the Type.GetType() method. (fixed - use AssemblyQualifiedName instead of FullName; assumes that interface and implementing class are in same assembly.)
One way would be to have a list of AssemblyQualifiedName pairs, with the first containing the base type and the second containing the child to be insantiated. It could be in your App.config or an XML file or whatever else is convenient. Read this list during start-up and use it to populate a Dictionary to use as a look-up table. For the key, you could use the AssemblyQualifiedName of the base, or perhaps the corresponding Type instance. For the value, you should probably consider getting the ConstructorInfo for the child type.
A better way to load the default types is to provide an add method that stores the type in a hash table. This decouples the dependency container from the registration logic.
You may choose later to change the registration code to read the types from some file or something.

C#: Can someone explain the practicalities of reflection? [duplicate]

This question already has answers here:
When do you use reflection? Patterns/anti-patterns
(17 answers)
Closed 9 years ago.
So I tried searching SO hoping someone had a good explanation of this, with no luck.
I asked another friend of mine a different question (which I've now forgotten) and his answer was simply "reflection" before he signed off.
I am still very new to the C# world, having been an amateur VB.net programmer (also JavaScript, ActionScript, and C), and am trying as hard as I can to grasp these advanced concepts.
There's lots of philosophical answers -- "application looking at itself" -- but they don't provide any practical hints on what is actually going on or how it is used within that context.
So, what is reflection, why is it important, and why/how do I use it?
Reflection provides the ability to determine things and execute code at runtime.
You don't have to use it if you don't want to, but it is extremely handy for dynamic behavior.
For example:
a) You can use reflection to configure your application by loading an external configuration file and starting services based on it. Your application wont have to know in advance about the classes that implement those services, as long as they conform to a specific interface or API.
b) Using reflection you can generate classes and code on the fly, which simplifies certain programming tasks since the programmer does not have to explicitly create all the needed code.
c) Reflection is also invaluable for programs that work by examining code. An example of that would be an IDE or a UI designer.
d) Reflection helps you reduce boilerplate code.
e) Reflection is handy for defining mini Domain Specific Languages (DSL) in your code.
(my defintion)
Reflection is the ability to write static code that executes code at run-time, that is normally determined at compile time.
For instance, I could call a class method to draw by compiling in that command eg:
pen.DrawLine()
or With reflection, I can first see if my object has a method called "drawline" and if so, call it. (Note this isn't the actual C# Reflection syntax)
if(pen.Methods.Contains("DrawLine"))
{
pen.InvokeMethod("DrawLine"))
}
I'm no reflection master, but I used reflection for a plug-in architecture.
With reflection I can load a .NET assembly (a dll in this case) at run time, find out all the types that are in the .NET Assembly, see if any of those types implement a specific interface, and if so, instantiate the class, to which I invoke the interface methods.
I know that use-case is a bit technical, but essentially reflection allows me to load plug-ins dynamically (ie at run-time), and lets me make type-safe calls to it.
The most common use of reflection is an extension of what used to be called RTTI (run-time type information) and was primarily the domain of C++ programmers.
Reflection is a side-effect of the way .net is built and that Microsoft elected to expose the libraries they used to create Visual Studio and the .net run-time to developers outside of Microsoft.
Most of the reflection library focuses on type discovery and creation that can be invoked at run-time. This allows for some very powerful self-referential code. Take the following example at the heart of our configuration management system (some bits deleted for clarity):
public static IMyCompanySetting UnwrapSetting(XmlNode settingNode)
{
string typeName = settingNode.Attributes["type"].Value;
string typeAssembly;
if(settingNode.Attributes["assembly"] != null)
{
typeAssembly = settingNode.Attributes["assembly"].Value;
}
Type settingType = null;
Assembly settingAssembly = null;
try
{
// Create an object based on the type and assembly properties stored in the XML
try
{
settingAssembly = Assembly.Load(typeAssembly);
if (settingAssembly == null)
{
return null;
}
}
catch (Exception outerEx)
{
try
{
settingType = GetOrphanType(typeName);
}
catch (Exception innerEx)
{
throw new Exception("Failed to create object " + typeName + " :: " + innerEx.ToString(), outerEx);
}
}
// We will try in order:
// 1. Get the type from the named assembly.
// 2. Get the type using its fully-qualified name.
// 3. Do a deep search for the most basic name of the class.
if (settingType == null && settingAssembly != null) settingType = settingAssembly.GetType(typeName);
if (settingType == null) settingType = Type.GetType(typeName);
if (settingType == null) settingType = GetOrphanType(typeName);
if (settingType == null) throw new System.Exception(
String.Format("Unable to load definition for type {0} using loosest possible binding.", typeName));
}
catch (Exception ex)
{
throw new CometConfigurationException(
String.Format("Could not create object of type {0} from assembly {1}", typeName, typeAssembly), ex);
}
bool settingIsCreated = false;
IMyCompanySetting theSetting = null;
// If the class has a constructor that accepts a single parameter that is an XML node,
// call that constructor.
foreach (ConstructorInfo ctor in settingType.GetConstructors())
{
ParameterInfo[] parameters = ctor.GetParameters();
if (parameters.Length == 1)
{
if (parameters[0].ParameterType == typeof(XmlNode))
{
object[] theParams = { settingNode };
try
{
theSetting = (IMyCompanySetting)ctor.Invoke(theParams);
settingIsCreated = true;
}
catch (System.Exception ex)
{
// If there is a pre-existing constructor that accepts an XML node
// with a different schema from the one provided here, it will fail
// and we'll go to the default constructor.
UtilitiesAndConstants.ReportExceptionToCommonLog(ex);
settingIsCreated = false;
}
}
}
}
This code allows us to create a limitless number of classes that implement IMyCompanySetting and serialize and deserialize themselves using XML. Then, given a chunk of XML that is the output of object serialization, the system can turn it back into an object, even if the object itself is from a library that the serialization library doesn't have staticly linked.
There are 3 things that reflect does here that would be impossible without it:
Load an assembly at run-time based on its name.
Load an object from an assembly at run-time, based on its name.
Call an object constructor based on signature for an object of a class that is not known at compile time.
Say you have two alternate implementations of an interface. You want to allow the user to pick one or the other, via a simple text config file.
With reflection, you can simply read the name of the class whose implementation you want to use from the config file (as a string), and instantiate an instance of that class.
Reflection lets you dig into an assembly and use it, no matter that you don't have it referenced later.
Consider a plug-ins system, in which the host doesn't know about the plug-ins it will hold; with Reflection (and the correct architecture), you can construct a simple solution achieving this.
Consider another scenario in which you must to call the method on an object given a string, Reflection gives you the approach to achieve this as well.
There are many other usages but i hope these two, open your apetite to this excellent feature of CLR
It's sometimes useful to be able to read properties or invoke methods of a class without knowing what properties or methods a class has at design time. The way to accomplish this is with reflection. As demonstrated by the code below, you can get a list of all properties on a class and retrieve their values without knowing anything about it at compile time. Or you can get a method by name, even if you don't know the name of the method at compile time, and invoke it via reflection. This would allow you, for example, to create a scripting language that operates on objects defined in another user-supplied DLL. (Of course you can also enumerate all methods in a class or retrieve a specific property by name, but these cases are not demonstrated in the code below.)
class Program
{
static void Main(string[] args)
{
UserDefinedClass udc = new UserDefinedClass();
udc.UserProperty = "This is the property value";
ClassTracer ct = new ClassTracer(udc);
ct.TraceProperties();
ct.CallMethod("UserFunction", "parameter 1 value");
}
}
class ClassTracer
{
object target;
public ClassTracer(object target)
{
this.target = target;
}
public void TraceProperties()
{
// Get a list of all properties implemented by the class
System.Reflection.PropertyInfo[] pis = target.GetType().GetProperties();
foreach (System.Reflection.PropertyInfo pi in pis)
{
Console.WriteLine("{0}: {1}", pi.Name, pi.GetValue(target, null));
}
}
public void CallMethod(string MethodName, string arg1)
{
System.Reflection.MethodInfo mi = target.GetType().GetMethod(MethodName);
if (mi != null)
{
mi.Invoke(target, new object[] { arg1 });
}
}
}
class UserDefinedClass
{
private string userPropertyValue;
public string UserProperty
{
get
{
return userPropertyValue;
}
set
{
userPropertyValue = value;
}
}
public void UserFunction(string parameter)
{
Console.WriteLine("{0} - {1}", userPropertyValue, parameter);
}
}
Reflection is using the code to examine the code itself. For example, instead of calling foo.DoBar() you could call:
foo.GetType().GetMethod("DoBar").Invoke(foo,null);
That seems like a round-about method of getting to the same destination, but it can also be used to do some black magic that might break the rules, like calling private methods on framework classes, for example. It can also be used to actually generate code and output new binaries, and a whole slew of things that are extremely useful to a small group of people.
For more information, check out the MSDN section on Reflection.
There are many cases in which the application should not assume much about itself and should look at runtime to see what it actually is. This is where reflection comes into the show. For example, ASP.NET makes no assumption about the membership provider you use except that it inherits the appropriate class. It uses reflection to lookup the class at runtime and instantiate it. This gives out a great deal of extensibility due to decoupling and decreasing dependencies between classes.
This is, of course, only a single use case for reflection. There could be many other cases where it might be very useful.
Andrew Troelsen, author of Pro C# 2008 and the .NET 3.5 Platform, defines reflection this way:
In the .NET universe, reflection is the process of runtime type discovery.
I'm not sure I could give you an accurate explanation of what that means, but I can tell you how I've used it.
I can put a user-defined attribute on an assembly (dll). Using reflection at run-time, I can inspect all of the assemblies in a certain directory location to see if they have this attribute defined. This can clue my application on how to use the assembly, say as a plug-in.
I've also used reflection to load and save application settings.
For what it's worth, unless you're using reflection, I'm not sure what it has to do with your GUI throwing exceptions.
About the only thing I know about C#
reflection is that it is annoying as
hell because all my GUI apps like to
throw incredibly annoying, pointless
"Exception has been thrown by the
target of an invocation" exceptions at
Application.Run(new frmMain());,
instead of stopping where the real
problem happened (as shown in the
innerException).
Your statement makes me believe you have few if any try/catch blocks anywhere in your application such that every exception is percolating back to the top of the call stack. If you are using Visual Studio 2005/2008 in debug mode, go into the Debug menu and select the Exceptions... menu option. Inside the Exceptions dialog, check the checkboxes under the Thrown column. Now, when you run your application and an exception is thrown, the debugger will break where the exception is thrown.
Let's say you have some business entities which all come derive from a base class called Entity. Let's also say that you need/want all the derived classes to be cloneable. You can implement a method "Clone" (interface ICloneable) on the base class which would loop through all the properties of the current class (although it is implemented at the Entity class) and copy them to the cloned object. This is a case where Reflection can really help. Because you can't know the name and the count of the properties at the base class. And you don't want to implement the method in all derived classes. However you might want to make the method virtual.
Other people have answered for
what is reflection, why is it important
So I will be answering following questions only.
How do I use it?
Through following namespaces
System.Reflection
System.Reflection.Emit
Why do I use it?
To invoke/inspect assembly types, members, properties
When you look at a product like Reflector, being able to inspect code structure is more than practical enough.
If you run fast and furious, maybe you're inheriting from an object and need access to a private field. You don't have source, but thats ok you have Reflection. (hacky I know)
A more legitimate use I've seen is to use reflection in implementing C# generics where I want to do some operation on the generic type that isn't otherwise available. The only operations available on a generic type are those made available with a generic constraint (ie, if you constrain the generic type to implement IFoo, you can use IFoo methods on instances of that class). Some operations though just aren't available- for instance I was taking a generic class that was supposed to have a particular non-default constructor. I couldn't constrain the generic method to only accept generic type parameters with that constructor, but at least I could try and use that constructor when implementing the generic via reflection.
I use reflection sparingly but it occasionally comes in real handy.
I have used reflection to implement a custom data bindings system.
For example, with my bindings API I can write the following:
Binding b = new Binding(textBox, "Text", myObject, "Text", BindingMode.Bidirectional);
Any changes to the text in the textBox object are detected by the Binding object (which attaches to the TextChanged event) and passed into the myObject.Text property. Changes to myObject.Text are detected (by its TextChanged event) and passed into the textBox.Text member.
I implemented this system using reflection. The Binding constructor is declared as:
Binding(object, string, object, string, BindingMode)
The system therefore works with any object (with one important proviso).
I inspect the first object and find the member corresponding to the named member in the first string (textBox and "Text", ie. does textBox have a member called "Text"). Repeat with the second object and string.
Proviso: for objects to be used in this scheme they must implement the informal requirement that any bindable property must have a corresponding PropertyNameChanged event. Happily, pretty much all the .Net UI components follow this convention.
I then inspect the object for the requisite PropertyNameChanged events, add event handlers to them, and everything is set.
NB. I implemented this in .Net 1.0, so it predates Microsoft's bindings implementation - which I have not yet got round to investigating.
Practical Application
Use reflection for aligning Data with objects, as in a data mapping situation. For example, you can map a database column to an object's property. If you were to write an Object Relational Mapper, you would need some way to get from a configuration setting (i.e. DatabaseColumnName maps to Class.MemberName) to the objects to which it referring.
Reflection is so named because it allows ones code to take a look at itself just like looking in a mirror.
As previously mentioned reflection may be used to create new instances using a class name. Serialization is also powered by reflection. In this case the code examines all the serializable fields and serializes those recursively until the entire graph has been consumed and its byte form written.
Reflection allows one to escape static typing at compile time by discovering types, methods, fields etc at runtime. Many dynamic languages on the JVM (not sure about CLR but id imagine the same is true) use reflection to dispatch methods.
In terms of a practical use for reflection we have used it to allow our customers to provide their own localisation.
With our applications we provide a local resource database that the client can work through providing language translation for all strings, menu items, dialog controls...etc. With this client translated database in place we then use reflection on application launch and iterate through all our controls and replace default language strings with the client supplied translated strings.
There are many uses for reflection that have already been detailed here but another use might be to log the state of an object including its private members for use in debugging.
Can you post some sample code which shows how you are performing reflection? Do you have the PDB files in the same location as the assembly on which you are using the reflection API's?
If so, then in Visual studio go to the Debug menu -->Exceptions and check the check box "Common Language runtime thrown". Run your application in debug mode. Hopefully the debugger should break at the point in your reflected assembly at which the real exception is being thrown.

Categories