Is it definitely a good practice to use it?
What are some possible situations in a project that need reflection?
Reflection in C# is used to retrieve metadata on types at runtime. In other words, you can use reflection to inspect metadata of the types in your program dynamically -- you can retrieve information on the loaded assemblies and the types defined in them.
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.
Because the common language runtime (CLR) stores information about the method's name in metadata, reflection must look inside metadata to learn which method on type "D" has the specified name. This logic alone is expensive.
Reflection is the process of describing the metadata of types, methods and fields in a code. The namespace System.Reflection enables you to obtain data about the loaded assemblies, the elements within them like classes, methods and value types.
The main value of Reflection is that it can be used to inspect assemblies, types, and members. It's a very powerful tool for determining the contents of an unknown assembly or object and can be used in a wide variety of cases.
Opponents of Reflection will cite that it is slow, which is true when compared to static code execution--however Reflection is used throughout the .NET framework, and provided that it's not abused it can be a very powerful tool in the toolkit.
Some useful applications:
Determining dependencies of an assembly
Location types which conform to an interface, derive from a base / abstract class, and searching for members by attributes
(Smelly) testing - If you depend on a class which is untestable (ie it doesn't allow you to easily build a fake) you can use Reflection to inject fake values within the class--it's not pretty, and not recommended, but it can be a handy tool in a bind.
Debugging - dumping out a list of the loaded assemblies, their references, current methods, etc...
There are many uses for reflection:
However, one of my favorite uses of reflection is to find properties that have been marked with attributes.
For example, I've written attributes that mark which properties in my classes should be indexed using Lucene. At runtime, I can look at any class, and figure out what fields need to get indexed by just querying the class for "marked" properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With