Its said that most high-level dynamically types languages are reflexive. Reflection (computer programming) on Wikipedia explains but it doesn't really give a very clear picture of what it means. Can anyone explain it in a simpler way by a relevant example?
To give you a example how to use Reflection in a practical way:
Let's assume you are developing an Application which you'd like to extend using plugins. These plugins are simple Assemblies containing just a class named Person:
namespace MyObjects
{
public class Person
{
public Person() { ... Logic setting pre and postname ... }
private string _prename;
private string _postname;
public string GetName() { ... concat variabes and return ... }
}
}
Well, plugins should extend your application at runtime. That means, that the content and logic should be loaded from another assembly when your application already runs. This means that these resources are not compiled into your Assembly, i.e. MyApplication.exe. Lets assume they are located in a library: MyObjects.Person.dll.
You are now faced with the fact that you'll need to extract this Information and for example access the GetName() function from MyObjects.Person.
// Create an assembly object to load our classes
Assembly testAssembly = Assembly.LoadFile(Application.StartUpPath + #"MyObjects.Person.dll");
Type objType = testAssembly.GetType("MyObjects.Person");
// Create an instace of MyObjects.Person
var instance = Activator.CreateInstance(objType);
// Call the method
string fullname = (string)calcType.InvokeMember("GetName",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, instance, null);
As you can see, you could use System.Reflection for dynamic load of Resources on Runtime. This might be a help understanding the ways you can use it.
Have a look on this page to see examples how to access assemblys in more detail. It's basically the same content i wrote.
To better understand reflection, think of an interpreter that evaluates a program. The interpreter is a program that evaluates other programs.
The program can (1) inspect and (2) modify its (a) own state/behavior, or the state/behavior of the interperter running it (b).
There are then four combinations. Here is an example of each kind of action:
1a -- Read the list of fields an object has
2a -- Modification of the value of one field based on the name of the field; reflective invocation of methods.
1b -- Inspect the current stack to know what is the current method that is executed
2b -- Modify the stack or how certain operations in the language are executed (e.g. message send).
Type a is called structural reflection. Type b is called behavioral reflection. Reflection of type a is fairly easy to achieve in a language. Reflection of type b is way more complicated, especially 2b--this is an open research topic. What most people understand by reflection is 1a and 2a.
It is important to understand the concept of reification to understand reflection. When a statement in the program that is interpreted is evaluated, the interpreter needs to represent it. The intepreter has probably objects to model field, methods, etc. of the program to be interpreted. After all, the interpreter is a program as well. With reflection, the interpreted program can obtain references to objects in the interpreter that represent its own structure. This is reification. (The next step would be to understand causal connection)
There are various kinds of reflective features and it's sometimes confusing to understand what's reflective or not, and what it means. Thinking in term of program and interpreter. I hope it will help you understand the wikipedia page (which could be improved).
Reflection is the ability to query the metadata the program that you wrote in run-time, For example : What classes are found inside an assembly, What methods, fields and properties those classes contains, and more.
.net contains even 'attributes', those are classes that you can decorate with them classes, methods, fields and more, And all their purpose is to add customized metadata that you can query in run-time.
Many time details depend on metadata only. At the time of validation we don't care about string or int but we care that it should not be null. So, in that case you need a property or attribute to check without caring about specific class. There reflection comes in picture. And same way if you like to generate methods on a fly, (as available in dynamic object of C# 4.0), than also it is possible using reflection. Basically it help to do behavior driven or aspect oriented programming.
Another popular use is Testing framework. They use reflection to find methods to test and run it in proxy environment.
It is the ability of a programming langauge to adapt it's behaviour based upon runtime information.
In the .Net/C# world this is used frequently.
For example when serializing data to xml an attribute can be added to specify the name of the field in the resultant xml.
This is probably a better question for programmers.stackexchange.com.
But it basically just means that you can look at your code from within your code.
Back in my VB6 days there were some UI objects that had a Text property and others that had a Description (or something other than 'Text' anyway, I forget). It was a pain because I couldn't encapsulate code to deal with both kinds of objects the same way. With reflection I would have at least been able to look and see whether an object had a Text or a Description property.
Or sometimes objects might both have a Text property, but they derive from different base classes and don't have any interface applied to them. Again, it's hard to encapsulate code like this in a statically typed language without the help of reflection, but with reflection even a statically typed language can deal with it.
Related
I'm working on a C# library (let's just call it "Foo" for the sake of this question). It has some needs very similar to standard .NET needs: for example, it provides some drawing services, and some conversion services.
For the sake of familiarity and users of the library being able to guess what things are called, I'd like to follow the .NET standard, and name these parts of the library Foo.Drawing and Foo.Convert (and so on). But I'm finding that in actual use, this causes pain. People almost always have "using System;" at the top of each file, and when using this library, they want to have "using Foo;" as well. But now they have two Drawing and two Convert modules, and hilarity ensues.
For example, now instead of just using Drawing.Color for a parameter or variable type, you have to explicitly spell out System.Drawing.Color, or the compiler complains that Foo.Drawing doesn't have a Color type. Similarly, you want to use a standard Convert.ToInt32, you have to say System.Convert.ToInt32, even though you're already using System, because otherwise it finds Foo.Convert and fails to find ToInt32.
I understand why all this is as it is, but I'm still new to the C# community, so I don't know which is the most standard solution:
Leave it this way, and expect users to use fully-qualified names where necessary?
Rename the conflicting modules to something else (maybe Foo.Graphics instead of Foo.Drawing, and Foo.Conversion instead of Foo.Convert)?
Use some prefix on the standard names (Foo.FDrawing and Foo.FConvert)?
Something else?
Any advice from you more experienced C# gurus will be appreciated!
You can use namespace aliasing :
using System;
using FConvert = Foo.Convert;
public class Bar
{
public void Test()
{
var a = Convert.ToInt32("1");
var b = FConvert.ToInt32("1");
}
}
One of the main usage of namespaces is to avoid name clashing.
It means that namespaces allow developers to create types with identical names, as long as the belong to different namespaces.
A library usually have at least a root namespace, and possibly nested namespaces that logically groups the related types.
Name your types as you wish, as long as the names are meaningful and represent what the type really are. A client of your library expects a type named Animal to represent an Animal, not something else. The same applies for naming namespaces.
However, avoid at all cost the names from System, since it will be really annoying for your library clients (as you described) to deal with conflicting names all over the place.
A common way to deal with conflicting namesapces inside a class is to use namespace aliasing:
using FooConvert = Foo.Convert;
using BarConvert = Bar.Convert;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Public Fields versus Automatic Properties
I figured this would be answered someplace, but I'm not finding it in the usual places. I was wondering, what is the benefit of doing this
private int _foo;
public int foo {get {return _foo;} set{_foo = value;}}
or
public int foo {get; set;}
over just
public int foo;
I can see the benefit if more complex manipulation was required, but what is the benefit for a simple case like this?
Actually, all the guidelines are about creating reusable libraries. There, when you create a property (using get/set), you also create the opportunity to later add code that is executed when someone gets or sets the value (like adding validation etc.) without changing the external definition of your code (and thus not needing to recompile the other libraries). But this has no value if you always recompile your whole solution and noone else is using the library.
Another benefit from using a property is that you can limit who can get or set the value. For example, everyone can get the value but only derived classes can set it (protected).
This said, it is still the recommendation to use properties always when they are public (as opposed to private fields).
I only expose fields when I need the best possible performance (like accessing the value million times in a row).
So to summarize
Benefits of properties (get/set) over fields:
Ability to add code later on without recompiling assemblies that reference this.
Ability to provide private/protected/internal set and public get (or any other combination).
Public fields are not CLS compliant.
Drawbacks of properties:
Slower to access (both read and write).
Can't pass as ref arguments to methods.
This question was asked many times here.
There is no clear benefit evidence fo these cases (no logic inside property).
Would say more, that using a field, you get some minimal (nano) speed benefit, but not relevant for 99.99% cases.
The guideline defined by MS suggests using properties, for expandibility and maintanability of your code. So following that guideline make easier work for someone that not familiar with the code to reading it.
See this Jon Skeet tutorial or When to use properties instead of functions for discussion of this matter. There is also a billion related questions and resources on this topic, which a Google/SE seach will expose.
I hope this helps.
According to me, using 'get-set' is providing a property. Basically you are implementing the concept of Encapsulation while providing the get-set property to a variable.
Imagine you have public variables in a class to store data.
But, if you need to do data validation, you are unable to do so with public variables in a class. Because you have no control over them. Outsiders, other programmers, anyone who access your project could edit those public variables in a class.
MAINLY, In order to control the access to data in your class we use properties. They are still variables but within the authority of your class. These variables may be from any data type (Eg. String, Int, Bool, Objects, etc)
Properties can be impemented using three main options, based on what/how you want to achieve with a property.
Get - access to the property and retrieve its value
Let - access to the property and update its value
Set - access to the property and used with objects
It's vital that one understands the real use of Get/Set methods. I agree with Tigaran on his comment.
If anyone is going to vode me down, I would like to know the reason!
I think you've answered your own question.
For simple cases like this, there is no real advantage. Automatic get/set methods are created by using the shorthand properties:
public int Foo { get; set; }
For more complex examples where transformation is needed then you have the flexibility to alter things using explicit get and set methods.
I'm currently working on DevExpress Report, and I see this kind of syntax everywhere. I wonder what are they? What are they used for? I meant the one within the square bracket []. What do we call it in C#?
[XRDesigner("Rapattoni.ControlLibrary.SFEAmenitiesCtrlTableDesigner," + "Rapattoni.ControlLibrary")] // what is this?
public class SFEAmenitiesCtrl : XRTable
Those are called Attributes.
Attributes can be used to add metadata to your code that can be accessed later via Reflection or, in the case of Aspect Oriented Programming, Attributes can actually modify the execution of code.
The [] syntax above a type or member is called an attribute specification. It allows a developer to apply / associate an attribute with the particular type or member.
It's covered in section 24.2 of the C# language spec
http://www.jaggersoft.com/csharp_standard/24.2.htm
They are called attributes. They are quite useful for providing metadata about the class (data about the data).
They are called Attributes, You can use them to mark classes, methods or properties with some meta-data that you can find by reflection at runtime.
For instance, one common one is Serializable which marks a class as suitable for conversion into an offline form for storage later.
It is called an attribute.
In this case, DevExpress is using custom attributes on their report classes.
If you're interested in why you want to create custom attributes, this article explains it.
Piling on to the previous answers, this is an attribute that takes a string value in its constructor. In this case, the '+' in the middle is a little confusing... it should also work correctly with:
[XRDesigner("Rapattoni.ControlLibrary.SFEAmenitiesCtrlTableDesigner,Rapattoni.ControlLibrary")]
When I create classes, simple constructors tend to be the norm. On one of my current projects, a movie library, I have a Movie domain object. It has a number of properties, resulting in a constructor as follows:
public Movie(string title, int year, Genre genre, int length, IEnumerable<string> actors)
{
_title = title;
_year = year;
_genre = genre;
_length = length;
_actors = new List<string>(actors);
}
This isn't terrible, but it's not simple either. Would it be worthwhile to use a factory method (static Movie CreateMovie(...)), or a perhaps an object builder? Is there any typical pattern for instantiating domain classes?
UPDATE: thanks for the responses. I was probably overthinking the matter initially, though I've learned a few things that will be useful in more complex situations. My solution now is to have the title as the only required parameter, and the rest as named/optional parameters. This seems the all round ideal way to construct this domain object.
If you are using .NET 4.0, you can use optional/named parameters to simplify the creation of an object that accepts multiple arguments, some of which are optional. This is helpful when you want to avoid many different overloads to supply the necessary information about the object.
If you're not on .NET 4, you may want to use the Object Builder pattern to assembly your type. Object builder takes a bit of effort to implement, and keep in sync with you type - so whether there's enough value in doing so depends on your situation.
I find the builder pattern to be most effective when assembling hierarchies, rather than a type with a bunch of properties. In the latter case, I generally either overloads or optional/named parameters.
Yes, using a factory method is a typical pattern, but the question is: Why do you need it? This is what Wikipedia says about Factory Methods:
Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.
So, the factory method pattern would make sense if you want to return subclasses of Movie. If this isn't (and won't be) a requirement, replacing the public constructor with a factory method doesn't really serve any purpose.
For the requirements stated in your question, your solution looks really fine to me: All mandatory fields are passed as parameters to the constructor. If none of your fields are mandatory, you might want to add a default initializer and use the C# object initializer syntax.
It depends.
If that is the only constructor for that class, it means all the properties are required in order to instantiate the object. If that aligns with your business rules, great. If not, it might be a little cumbersome. If, for example, you wanted to seed your system with Movies but didn't always have the Actors, you could find yourself in a pickle.
The CreateMovie() method you mention is another option, in case you have a need to separate the internal constructor from the act of creating a Movie instance.
You have many options available to your for arranging constructors. Use the ones that allow you to design your system with no smells and lots of principles (DRY, YAGNI, SRP.)
I don't see anything wrong with your constructor's interface and don't see what a static method will get you. I will have the exact same parameters, right?
The parameters don't seem optional, so there isn't a way to provide an overload with fewer or
use optional parameters.
From the point-of-view of the caller, it looks something like this:
Movie m = new Movie("Inception", 2010, Genre.Drama, 150, actors);
The purpose of a factory is to provide you a customizable concrete instance of an interface, not just call the constructor for you. The idea is that the exact class is not hard-coded at the point of construction. Is this really better?
Movie m = Movie.Create("Inception", 2010, Genre.Drama, 150, actors);
It seems pretty much the same to me. The only thing better is if Create() returned other concrete classes than Movie.
One thing to think about is how to improve this so that calling code is easy to understand. The most obvious problem to me is that it isn't obvious what the 150 means without looking at the code for Movie. There are a few ways to improve that if you wanted to:
Use a type for movie length and construct that type inline new MovieLength(150)
Use named parameters if you are using .NET 4.0
(see #Heinzi's answer) use Object Initializers
Use a fluent interface
With a fluent interface, your call would look like
Movie m = new Movie("Inception").
MadeIn(2010).
InGenre(Genre.Drama).
WithRuntimeLength(150).
WithActors(actors);
Frankly, all of this seems like overkill for your case. Named parameters are reasonable if you are using .NET 4.0, because they aren't that much more code and would improve the code at the caller.
You gave a good answer to your own question, it's the factory pattern. With the factory pattern you don't need huge constructors for encapsulation, you can set the object's members in your factory function and return that object.
This is perfectly acceptable, IMHO. I know static methods are sometimes frowned upon, but I typically drop that code into a static method that returns an instance of the class. I typically only do that for objects that are permitted to have null values.
If the values of the object can't be null, add them as parameters to the constructor so you don't get any invalid objects floating around.
I see nothing wrong with leaving the public constructor the way it is. Here are some of the rules I tend follow when deciding whether to go with a factory method.
Do use a factory method when initialization requires a complex algorithm.
Do use a factory method when initialization requires an IO bound operation.
Do use a factory method when initialization may throw an exception that cannot be guarded against at development time.
Do use a factory method when extra verbage may be warranted to enhance the readability.
So based on my own personal rules I would leave the constructor the way it is.
If you can distinguish core data members from configuration parameters, make a constructor that takes all of the core data members and nothing else (not even configuration parameters with default values—shoot for readability). Initialize the configuration parameters to sane default values (in the body of the method) and provide setters. At that point, a factory method could buy you something, if there are common configurations of your object that you want.
Better yet, if you find you have an object that takes a huge list of parameters, the object may be too fat. You have smelled the fact that your code may need to be refactored. Consider decomposing your object. The good literature on OO strongly argues for small objects (e.g. Martin Fowler, Refactoring; Bob Martin, Clean Code). Fowler explain how to decompose large objects. For example, the configuration parameters (if any) may indicate the need for more polymorphism, especially if they are booleans or enumerations (refactoring "Convert Conditional to Polymorphism").
I would need to see the way that your object is used before giving more specific advice. Fowler says that variables that are used together should be made into their own object. So, sake of illustration, if you are calculating certain things on the basis of the genre, year and length, but not the other attributes, those together may need to be broken out in to their own object—reducing the number of parameters that must be passed to your constructor.
As for me - all depending on your domain model. If your domain model allows you to create simple objects - you should do it.
But often we have a lot of composite objects and the creation of each individually is too complicated. That's why we`re looking for the best way to encapsulate the logic of composite object creation. Actually, we have only two alternatives described above - "Factory Method" and "Object Builder". Creating object through the static method looks a bit strange because we placing the object creation logic into the object. Object Builder, in turn, looks to complicated.
I think that the answer lies in the unit tests. This is exactly the case when TDD would be quite useful - we make our domain model step-by-step and understand the need of domain model complexity.
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.