Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection in C#?

Tags:

c#

reflection

wpf

I have recently made the transition from a Java web developer to a C# application developer doing mostly WPF applications. I used to use Spring MVC with Java, where a lot of the code structure was preempted and setup for me. Since I have made the transition to WPF, my applications are reliant on my ability to setup reusable, decoupled code.

I have been trying to improve my skills with certain areas of design including Generics,Design Patterns and Reflection.

I am well aware of what all these are and for Generics and Design patterns, I am fairly well at applying what I consider best practices(although this is up in the air).

What I am not too familiar with is reflection. I know what reflection is, and I know how to do it to do tasks such as dynamic assembly loading,method and class invocation,etc.

What I do not understand is examples how this might be able to help me.

I constantly hear how reflection can be really helpful if you know how to use it. When I try to research the topic, I only find tutorials and reference of how to do it, instead of the good that it can be used for.

My question is what can I look to as a WPF Developer in using reflection for that will help me, and/or is there a place, or reference that can give me more then just the syntax of using reflection, but also real world examples and/or best practices?

like image 294
TheJediCowboy Avatar asked Feb 26 '11 17:02

TheJediCowboy


People also ask

What is reflection in C?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

Does C support reflection?

Reflection is supported through the common language runtime, not by the Microsoft C++ compiler. Although you used this code to inspect an assembly that you defined, you can also use this code to inspect .

What is reflection in language?

A language supporting reflection provides a number of features available at runtime that would otherwise be difficult to accomplish in a lower-level language. Some of these features are the abilities to: Discover and modify source-code constructions (such as code blocks, classes, methods, protocols, etc.)

What do you use reflection for in programming?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.


2 Answers

Reflection is a powerful API. At its basic level, reflection allows you to:

  • Inspect the types contained in an assembly
  • Inspect the members of a given type, including metadata (via attributes)
  • Dynamically invoke these members

If you're using the binding mechanism within WPF to bind to normal business objects, then you're already using reflection. The binding API, after looking for more formal binding mechanisms (inheriting from DependencyObject, having a custom type descriptor, etc.), will use reflection to get and set the values of properties on your business object (or ViewModel).

For example, say you have this class

public class Customer { public string Name { get; set; } }

And your WPF control (view) binds to a collection of these Customer objects, and has a label control that binds to the Name property. All of this is defined in XAML, but at runtime the code would look something like this:

var value = dataObject.GetType().GetProperty("Name").GetValue(dataObject, null);

This would obtain the value from the bound object--without knowing anything about its type--and allow the control to display it in the appropriate fashion. Likewise:

dataObject.GetType().GetProperty("Name").SetValue(dataObject, "Bob", null);

Would set the value of the property on that object to "Bob", again without knowing anything about its type.

As for how it can help you directly, use cases for this are comparatively rare. If you find yourself in a position to need to use reflection in order to accomplish what you need, you may want to consider refactoring the code; it's always better (in a statically-typed language like C#) to go with code that follows static typing versus using dynamic invocation via reflection. While metadata inspection is fairly cheap, it takes a lot more processing to invoke a member by reflection than it does through ordinary means.

The short answer is, honestly, if you're asking how it can help you, it's best to assume that--for now--it can't.

like image 135
Adam Robinson Avatar answered Sep 20 '22 21:09

Adam Robinson


Reflection can be used for things like:

  1. ORM (object relational mapper): mapping properties of an object to columns in database table
  2. Model Binding: Mapping data posted from a web form to properties of an object
  3. Copying: mapping business objects to DTOs
  4. Serializing: mapping objects to and from json or xml
  5. MVC framework: inspecting urls and creating controllers objects based on a naming convention
  6. Validation: Inspecting objects for Attributes and enforcing validation rules

Example:

public class Customer : Entity
{
    [Required]
    public string Name { get; set; }
}

And then something else can look for those attributes, like a validator:

public class Validator
{
    public ValidationResult Validate(Entity entity)
    {
        // use reflection to find validation attributes and enforce them
    }
}
like image 34
Mike Valenty Avatar answered Sep 21 '22 21:09

Mike Valenty