views:

143

answers:

8

Possible Duplicate:
Reflection. What can we achieve using it?

I see plenty of examples of using reflection in c#, but I'm not sure exactly what all it is mainly used for in c#. So when do you use it?

+1  A: 

There are lots of ways to use it. One way I use it is in unit testing when I need to corrupt some private variable to get a unit test to fail (to simulate failure test scenarios). For example, if I want to mock having a database connection fail, then I could use the below method to change the connectionString private variable in a class that works with the DB. This would cause the DB connection to fail when I tried to connect to the DB, and in my unit test I can verify that the proper exception is thrown.

Ex:

/// <summary>
/// Uses reflection to set the field value in an object.
/// </summary>
///
/// <param name="type">The instance type.</param>
/// <param name="instance">The instance object.</param>
/// <param name="fieldName">The field's name which is to be fetched.</param>
/// <param name="fieldValue">The value to use when setting the field.</param>
internal static void SetInstanceField(Type type, object instance, string fieldName, object fieldValue)
{
    BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
        | BindingFlags.Static;
    FieldInfo field = type.GetField(fieldName, bindFlags);
    field.SetValue(instance, fieldValue);
}
dcp
+1  A: 

A real-world case:

A function that when passed the name of the namespace looks through all classes in the namespace and if it finds a function "SelfTest" in the class it calls it, instantiating an object if need be.

This lets me declare test functions as part of the objects and not have to worry about maintaining a list of tests.

Loren Pechtel
A: 

See how Microsoft uses it in a web.config for example :)

I used it when I have to filter items (using ItemFilter property) from Autocompletebox. The ItemSource was setted with Linq. As each item was of AnonymousType, I used Reflection to get properties and perform the filter I desire.

+1  A: 

Relection is a technique which allow developers to access Metadata of the type/instance at runtime.
The most common usage is defining CustomAttribute and use it at run time. CustomAttribute has been used in ORMs, ASP.Net ActionFilter, Unit Testing Framework, etc.

Cory Charlton answered very well in this question:

http://stackoverflow.com/questions/1897712/reflection-what-can-we-achieve-using-it

Soe Moe
+1  A: 

In general anything that touches System.Type type can be considered reflection. It is often useful(amongst other things) for all sorts of Convention over Configuration scenarios.

Consider an example where you want to create an instance of a type that you don't know until runtime:

public interface IVegetable {
   public float PricePerKilo {get;set;}
}

public class Potato : IVegetable {
   public float PricePerKilo {get;set;}
}

public class Tomato : IVegetable {
   public float PricePerKilo {get;set;}
}

public static class Program {
  public static void Main() {
    //All we get here is a string representing the class
    string className = "Tomato";
    Type type = this.GetType().Assembly.GetType(className); //reflection method to get a type that's called "Tomato"
    IVegetable veg = (IVegetable)Activator.CreateInstance(type);
  }
}
Igor Zevaka
+1 Never heard of "Convention over Configuration", sounds like a good idea. I've done similar stuff myself, but this takes what I was doing in my experiments and goes 10 steps further.
Grant Peters
A: 

I use it for validation/encoding, like looking through all the strings in a class and changing them to HTML safe strings before I send over to a web view. Similary when retrieving the data from the view i run though a encoding/regex to make sure only safe html characters are used.

The other way is to write plugins in C# where you want the functionality to be known at runtime. example from code project: http://www.codeproject.com/KB/cs/pluginsincsharp.aspx

Stephen Lee
A: 

I've used it to compile lists of controls within pages (from a totally separate page) of a web application.

It can be used to dynamically instantiate classes, analyze assemblies, type checking...

It is what it says, a reflection, it allows a program to look at itself.

Mike Cellini