Click here to Skip to main content
15,881,715 members
Everything / Reflection

Reflection

reflection

Great Reads

by matt warren
Why is Reflection slow?
by n.podbielski
If you want to optimize code, which is based on Reflection, delegates may be the thing you are looking for. In this part are explained generic methods and events.
by Eric Lynch
Extends .NET reflection to decode the byte array returned by System.Reflection.MethodBody.GetILByteArray(), discusses the techniques to achieve this, and provides a brief primer on .NET reflection.
by Dev Leader
In this article, I’ll provide you with 4 simple code examples illustrating how reflection works in C#.

Latest Articles

by Dev Leader
In this article, I’ll provide you with 4 simple code examples illustrating how reflection works in C#.
by JBartlau
This article provides an overview of Visual Studio's integration of combit's report generator List & Label.
by Jaume González
Solution using reflection to dynamically load and execute C# code in a workflow context
by Bill Menees
Use .NET's TypeToTypeInfoMarshaler to get a full .NET type with member information from an IDispatch-based COM object.

All Articles

Sort by Score

Reflection 

15 Dec 2016 by matt warren
Why is Reflection slow?
6 Sep 2016 by n.podbielski
If you want to optimize code, which is based on Reflection, delegates may be the thing you are looking for. In this part are explained generic methods and events.
15 May 2018 by Eric Lynch
Extends .NET reflection to decode the byte array returned by System.Reflection.MethodBody.GetILByteArray(), discusses the techniques to achieve this, and provides a brief primer on .NET reflection.
1 Mar 2024 by Dev Leader
In this article, I’ll provide you with 4 simple code examples illustrating how reflection works in C#.
4 Feb 2012 by Huisheng Chen
Using reflection to dynamically verify if an assembly is in debug or release compilation
29 Sep 2021 by benji_dv
How to clear all events is quite simple. It needs a finger of reflection...
2 Feb 2012 by Dean Oliver
How we can harness the power of MEF and extend it by way of generics.
4 Nov 2021 by #realJSOP
A tool to generate model and viewmodel classes directly from your selected database
2 Sep 2014 by DiponRoy
Let’s see how to make a simple model or Entity mapper using reflections in C#
30 Jun 2016 by Simon Gulliver
Really? Then why is so much effort wasted writing boilerplate which can be more accurately and efficiently automated?
1 Oct 2014 by Yuriy Magurdumov
PropertyMapper allows mapping object properties to string keys and accessing property values based on those string keys
6 Mar 2017 by Michael Doleman
A simple DAL with an integrated, lightweight model for database seeding from a JSON source, using the code-first method in Entity Framework.
5 Jun 2012 by VJ Reddy
It is possible to Invoke a method using named parameters as explained here http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx[^]In one of the over loads of the Type.InvokeMember method we can pass an array of namedParameters as explained here...
3 Dec 2012 by Vasil Trifonov
Getting console output within a unit test
17 Feb 2015 by PFalkowski
The way of calculating amount of memory occupied by some object in C#.NET
25 Jan 2012 by Dean Oliver
An alternative to Activator.CreateInstance
11 Apr 2012 by Sergey Alexandrovich Kryukov
One approach is using such an interesting thing as System.Reflection.Emit.DynamicMethod; please see:http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx[^].The idea is: you don't have to create methods which are counted as being declared in certain type. In...
5 Jun 2012 by Manfred Rudolf Bihy
Yes this is possible. You will have to use the more elaborate method Type.InvokeMember[^].The page describing the BindingFlags[^] parameter of the Type.InvokeMember method has a quite elaborate example with different usage scenarios. Search the page for this string: Invoking a method with...
11 Jul 2012 by Sergey Alexandrovich Kryukov
Ah, finally I got it. Maybe an interesting problem, but not making much sense.Here is the thing: you are facing some limitation which is not 100% logically required. Your code sample looks convincing (not many people will really understand your explanation of it, it just so happens that I am...
25 Jul 2014 by Kishor Deshpande
Methods which facilitate the conversion from string to value type
15 Jun 2016 by Allen C. Copeland Jr
Grokking the CLI - Part 1: Meta Mayhem
28 Feb 2012 by Marc Clifton
Sounds like a stupid question, but here's the problem.I have, say:IEnumerable t;obviously, typeof(t).FullName will give me:System.Collections.Generic.IEnumerable`1[[System.Data.DataRow, System.Data, Version=4.0.0.0, Culture=neutral,...
29 Feb 2012 by Pete O'Hanlon
A rough and ready method (knocked together in a couple of minutes) would be to do this:public class TypeResolver{ public string EvaluateType(Type type) { StringBuilder retType = new StringBuilder(); if (type.IsGenericType) { string[] parentType =...
8 May 2012 by Sergey Alexandrovich Kryukov
The most basic steps are:using System;using System.Reflection;//...class Sample { int[] array; // intentionally left private, to demonstrate the effect of Reflection} //class Sample//...Sample sample = new Sample(); // could do it using Reflection, via invocation of...
15 Aug 2012 by Sergey Alexandrovich Kryukov
The idea is very simple. You almost got it, should just think about it.The kind of late binding you use is of the level of plug-in (your "registered" DLL) and the plug-in architecture. You need to look at it as at the whole architecture, and it all will be clear to you. The think is: the...
22 Jan 2013 by Sergey Alexandrovich Kryukov
Ultimately, Reflection.Emit is the best way to go. If you found that it is unsuitable, you probably missed something. I don't know what exactly you are trying to achieve, so just some hints:You don't have to create a whole separate assembly with Emit. You may choose to create separate...
5 May 2015 by Sergey Alexandrovich Kryukov
"Append a DLL" is nothing but absurd. You can always load an assembly (assembly, not "DLL") using...
7 May 2015 by Sascha Lefèvre
You need to provide the full path and file name to Assembly.LoadFrom(..)[^], e.g.:Assembly assembly = Assembly.LoadFrom(@"c:\test\MyAssembly.dll");But you only provided a path (or, if "plugin" is the name of the file, you have to append ".dll" or, unlikely but possible, ".exe").Edit...
26 Feb 2016 by Pavel Sinkevich
How to programmatically change schema name in database project before deployment
23 Jul 2019 by honey the codewitch
if (val.GetType().FullName.StartsWith("System.Tuple`")) System.Diagnostics.Debugger.Break(); This works, but it's dodgy. I'm looking for something having to do with the generic type definition, like with typeof(Tuple) but it doesn't work. I can't care how many arguments the tuple has. I...
23 Jul 2019 by Richard Deeming
If you're using .NET 4.7.1 or later, you could test whether it implements the System.Runtime.CompilerServices.ITuple interface[^]: if (value is System.Runtime.CompilerServices.ITuple) This will also detect the new ValueTuple types. Otherwise, you'd need to get the generic type definition...
16 Feb 2012 by SilenthillpH
string formTypeFullName = string.Format("{0}.{1}", this.GetType().Namespace, typeName);Type type = Type.GetType(formTypeFullName, true);Form item = (Form)Activator.CreateInstance(type);item.ShowDialog();type name need full name like this -> HouseDataBase.TObjectForm
7 Mar 2012 by Dean Oliver
You invoke it like any other method through reflection. except that the returned value will be copied back into the parameter array so you can access it from the calling function. Eg;class Program { delegate int Run(int a, int b, out int sum); private static...
25 Mar 2012 by Sergey Alexandrovich Kryukov
The question has little to do with Reflection. This problem is solved using the classes System.Diagnostics.StackTrace and System.Diagnostics.StackFrame.Please...
4 Apr 2012 by Clifford Nelson
This might be of some help: http://www.jarloo.com/c-formula-evaluator/[^]. It uses regular expressions to parse the text.
9 Jul 2012 by Matt T Heffron
This is an alternative for "Custom String FormatWith using Reflection"
13 Jan 2013 by Sergey Alexandrovich Kryukov
First wrong point in the I can see in your code is this:if (t.GetInterfaces().Contains(typeof(IHeaderBarComponent))) ...Is your purpose selecting the type which implements IHeaderBarComponent?This is how it's done:System.Type headerBarComponentType =...
31 May 2013 by Zoltán Zörgő
Well, not exactly like that, see: http://kalpeshshirodker.wordpress.com/2007/08/06/functions-with-variable-parameters-in-c/[^] and this http://stackoverflow.com/questions/2062883/is-there-a-way-to-enumerate-passed-method-paramters[^] options.
10 Jan 2014 by Karthik_Mahalingam
Try like this.. if (ti.Name == "Class2") { MethodInfo TestMethod1 = ti.GetMethod("TestMethod1"); MethodInfo TestMethod2 = ti.GetMethod("TestMethod2"); var instance = Activator.CreateInstance(ti); string value...
13 Jan 2014 by #realJSOP
I have an entity framework model in a MVC app.The user will select a table by table name, and the table data will be retrieved for display in a grid.I've gotten this far. See the code comments for where I'm stuck. Now that I have the type, how do I do what I need to do?private void...
1 Jul 2014 by JIANGWilliam
This article introduces a handy way to get the calling Testing Assembly from a called Assembly
20 Feb 2015 by PIEBALDconsult
That's a terrible idea. I could write Method_C and call Method_B from it. How can you expect Method_B to be able to use whatever parameters Method_C has? Or would you want to somehow detect whether or not Method_B was called from Method_A and throw an execption if it wasn't?Method_A...
9 Mar 2015 by Sergey Alexandrovich Kryukov
What part of this error message can be unclear? Let's see…In first line, you use this function: https://msdn.microsoft.com/en-us/library/w3f99sx1%28v=vs.110%29.aspx[^].I have no idea why, but you were lucky enough to have this string recognized as some really existing type. But...
16 Jun 2016 by Allen C. Copeland Jr
Grokking the CLI - Part 2: Meta Meanderings
21 Jul 2016 by Bernhard Hiller
Quote:and i need to pass body as parameter to another methodThat other method needs to be generic, too; or at least accept a type compatible with T. Otherwise, the encapsulation in the generic class does not make sense.
18 Aug 2017 by Mehdi Gholam
First don't use reflection unless you need it and you know what you are doing, so if your method counts is low use a switch statement: switch(comm.Method) { case "method1" : this.Method1(comm.Data); break; ...// and so on } You can also use a Dictionary with...
19 Jun 2022 by Shmuel Zang
Due to type erasure, the compiler replaces the generic type (T) with its first bound (Object in our case). Therefore, when I tried to get the type of the defined generic field, I got Object (and not Person as I expected). So, it looks like it's...
18 Aug 2019 by rohitsies
CSV file generator using simplistic approach
9 Sep 2011 by Mehdi Gholam
The video property has an Editor defined on it, and that editor is responsible for the readonly checking, try removing it.
1 Nov 2011 by Jephunneh Malazarte
Generic class:public class GenericEntityMapping{ public T Map(XmlNode xNode, T entityObject) { //FYI. //PropertyInfo[] entityProperties = typeof(T).GetProperties(); //foreach (PropertyInfo pInfo in entityProperties){...} //somewhere in...
1 Nov 2011 by Sergey Alexandrovich Kryukov
For a type, being generic and begin static are not related. Both generic and non-generic types can be static or not static.—SA
1 Nov 2011 by Jephunneh Malazarte
Hello SAKryukov,Thanks for the quick reply.I found the solution:MethodInfo method = typeof(GenericEntityMapping).GetMethod("Map");MethodInfo generic = method.MakeGenericMethod(Type.GetType(pInfo.PropertyType.FullName));object[] objParam = { node,...
7 Jan 2012 by Sergey Alexandrovich Kryukov
Your code is not quite clear to me, but providing a data structure that looks like an array for a user and is not an array in implementation is quite easy:internal struct Element {/*..*/} //or classclass ElementContainer { internal Element Add(Element element) {/*...*/ return...
25 Jan 2012 by Sergey Alexandrovich Kryukov
It looks like what you need is the plug-in architecture.In this case, referencing of assembly is not an option. You can load an assembly during run-time using System.Reflection or you can compile assembly out of source code and load it. Behind the scene, this second option is actually...
7 Feb 2012 by Sergey Alexandrovich Kryukov
First, let's look just at the title of this question. It looks you are missing something important.Let's look at all possible targets of the attributes. Please read this: http://msdn.microsoft.com/en-us/library/system.attributetargets.aspx[^].All those targets are classified into...
1 Mar 2012 by Not Active
Generics are OK for some things but not for others. Trying to make a one size fits all application has been attempted without success many times. In this case, as you found out, it is not supported. The compiler needs some information upfront to build the proper IL and late binding doesn't...
9 Mar 2012 by Rohit Prakash Srivastava
I created a class library project and added X.dll and y.dll and I am building it. It creates Classlibrary.dll. This classlibrary.dll consists of X.dll and y.dll.Now I am creating a new Winforms application and adding ClassLibrary.dll as a reference. Now if I run the Winforms application I...
4 Apr 2012 by ProEnggSoft
This Code Project articlemath / function / boolean /string expression evaluator[^]may also be helpful.
11 Apr 2012 by petBorromeo
Hi All,I am interested to know how to do the following with Reflection.Emit in C#.I have an assembly in my program already loaded and from it I can read all the classes and methods inside of it. However, I would like to add more methods in this current Assembly. I understand the...
8 May 2012 by NiloPaim
I have a Windows Forms TreeGrid, populated via reflection applied on some bussiness classes I wrote. Each line of the TreeGrid shows my class' properties, along with a column where I can edit the valueof the property.My problems arise when I have "public xxx[]" on my class. I can populate...
19 Jun 2012 by Sergey Alexandrovich Kryukov
The term concept or virtual and overridden method/properly is related to a type (a class), not an instance of a class.Therefore, the question makes no sense and just demonstrates that you did not get how OOP works in principle, well, not just yet; you need to understand it thoroughly,...
31 Jul 2012 by Zoltán Zörgő
Of course you can. Start here: http://martfish.wordpress.com/2011/08/23/using-reflection-to-open-a-form-by-name/[^].But be aware that you need to add an extra interface (formal or not) to have communication between instantiating class and instantiated form - the argument passed to the...
30 Oct 2012 by Guirec
You can try something like:var t = Type.GetType("the full name of your class here");if (t != null){ // the type is present so your assembly is there var methodToCall = t.GetMethod("Name of the method to call"); // invocation var result =...
6 May 2013 by Sergey Alexandrovich Kryukov
Please see the methods System.Type.GetProperty: http://msdn.microsoft.com/en-us/library/system.type.aspx[^].However, you are getting into a solution which is pretty hard to implement in a universal way, and the performance is going to be low, because using reflection over and over is too...
31 May 2013 by PIEBALDconsult
You can dopublic void dosomething(params object[] args)but I wouldn't without really good reason.
31 May 2013 by Sergey Alexandrovich Kryukov
[After OP's clarification added to the question]After clarification, the problem started to resemble Service Contracts, as they are used in WFC. I think it can be a good food for...
15 Jun 2013 by Ron Beyer
Ok... I found it...The problem was this line:internal static void ApplyResource(ref Control c, string fullControlName) { string resourceName = fullControlName + ".Text"; string value = c.Text; try { ...
15 Jul 2013 by Sergey Alexandrovich Kryukov
First of all, you should avoid doing it by any names, because it will require using string constants, which cannot be checked up by the compiler. This way, any solution using names will be really bad for maintenance.The really good option is to define "plug-in interfaces" and implement it by...
24 Oct 2013 by Trapper-Hell
Not the best way to do it, but since no one else provided any suggestions, here's what I did:1. The LoaderApp loads all the referenced assemblies in memory (as shown in the code snippet of the original question2. The loaded Assemblies are passed to a private method implemented in the...
7 Apr 2014 by BillWoodruff
See if this helps you get going. Put a ListBox, named 'listBox1, on a Form, add this method:// requiredusing System.Reflection;private void ClearListBox(){ Control theControl = listBox1; Type cType = theControl.GetType(); PropertyInfo[] cProps =...
4 Nov 2014 by Sinisa Hajnal
The method DisplyDetails you provide is private and therefore available only to Page1If you want to call it from Page2, you should either make it public and instantiate page1 in page2 or make it static (but then you cannot use instance variables).I would suggest pulling the method out in...
2 Feb 2015 by Sergey Alexandrovich Kryukov
First of all, this is not the purpose of reflection to create some instance of some type using hard-coded type name. Getting a type from string is rarely used (by serialization, for example) and fairly often abused. But I can understand if you are doing some exercises, for understanding.None...
7 Aug 2015 by Sergey Alexandrovich Kryukov
Yes, you can do it exactly this way: https://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getindexparameters%28v=vs.110%29.aspx[^].This documentation tells you that it always returns the array, but its length can be zero, which happens if the property is not indexed.—SA
9 Oct 2015 by Sergey Alexandrovich Kryukov
This is not just System.Reflection, this would be System.Reflection.Emit. And if you really need to construct a class, not just DynamicMethod, you will need to create the whole assembly on the fly. You will have to learn it...
15 Oct 2015 by BillWoodruff
"Dynamic Type Using Reflection.Emit" by Abhishek Sur [^].You can create new Objects of any Type at run-time using Reflection and the System.Reflection.Emit namespace; however this is a pain in the butt to do (not something I've had a requirement to do, so far), and computationally...
16 Dec 2015 by F-ES Sitecore
When using GetType by name you need to give a fuller qualified name.GetType("MyNamespace.MyClass, MyAssembly")SoGetType("HR.Core.Employee, HR.Core")above I am assuming the Employee class is an assembly called HR.Core, but it might not be. Example the project properties of the...
7 Mar 2016 by Sascha Lefèvre
Yes, you need to dynamically build an expression tree for that. But there already are some solutions for this which you could use:Build Lambda Expressions Dynamically[^]Dynamic Expresso[^]LINQ and Dynamic Predicate Construction at Runtime[^]Build Where Clause Dynamically in...
30 Mar 2016 by phil.o
You have to load the assembly you are trying to use reflection on:string path = @"..\..\ConsoleApplication11\bin\Debug\ConsoleApplication11.exe"; // Put the right path to the assembly you are trying to load hereAssembly consoleApp11 = Assembly.LoadFile(path);Assembly...
22 Jul 2016 by Philippe Mori
You should probably add the following function to your Envelope class:public abstract Type GetBodyType();And then implement it in the derived class Envelope:return typeof(T);Or maybe you need to reconsider the whole design... Are you trying to convert a pattern from another language?
5 Sep 2016 by Richard Deeming
When you create a delegate pointing to an instance method, you have to provide the "Me" object which will be used when the delegate is invoked. Because you haven't done that, and you've specified False for the throwOnBindFailure parameter, your delegate instance will be set to Nothing.There...
7 Feb 2017 by discompsys
An easy way to allow local objects with direct access to invoke methods on a class, but prevent them from being part of the public API, for remote invocation.
23 Mar 2017 by Richard Deeming
Based on some crude testing, I suspect the problem is actually the other way round: you can create the delegate when the method hasn't been overridden, and you can't create the delegate when the method has been overridden.Class Foo Protected Overridable Sub Click() ...
10 Apr 2018 by #realJSOP
When I want to do something like that, I create a method that performs the desired action, and call it from both event handlers. No reflection or weird programming is required (or desired).
10 Apr 2018 by Afzaal Ahmad Zeeshan
As mentioned in Solution 1, there are many other ways of doing this—most importantly, you can change the overall architecture of this too, make them click something else and then initiate the function on other two operations. That would be much simpler. In the reflection, you can work around...
5 Jul 2018 by Graeme_Grant
As recommended by johannesnestler, I like to use MEF[^] for apps like these. This is going to be a long answer but hang in there, it will be worth it... I've made a couple of examples for you so that you have an idea of how you could do it using MEF: 1. Console Solution - This demonstrates...
10 Jun 2020 by Richard Deeming
As shown, your DataEntries class doesn't have any properties, so there's nothing to drill down into. Assuming you actually have some properties in there: public class DataEntries { public class UserObjects { public string UserId...
8 Jul 2021 by Richard MacCutchan
I am not a kotlin expert, but ... crewCrewCrew.forEach { mammalFactCheck(it, Mammal::vertebraeCount) mammalFactCheck(it, Mammal::knownSpeciesCount) } ... appears to be a loop which iterates over the entries in the crewCrewCrew list...
14 Jul 2022 by Jaume González
Solution using reflection to dynamically load and execute C# code in a workflow context
30 Sep 2022 by Richard MacCutchan
Look at the error message: Exception in thread "main" java.lang.NoClassDefFoundError: javax/mail/Authenticator You need to find out why that class is not found. [edit] Probably because Authenticator (Java(TM) EE 7 Specification APIs)[^] is an...
22 Oct 2023 by Member 16121670
Hi, I know it's a bit late to answer this question, but you could use reflection to construct the generic method with something similar to this: //var typeO = objeto.GetType(); //here is the problem. The var typeO is not accepted. //var...
19 Jun 2022 by Shmuel Zang
For getting a type's name in Java we call the getTypeName function on the type's class. For example, this line of code: System.out.println(String.class.getTypeName()); will print: java.lang.String But, when dealing with generic types, the...
6 Apr 2011 by Sergey Alexandrovich Kryukov
Strictly speaking, you cannot calculate execution of arbitrary code based on static analysis of this code. In general case, it is even impossible to say if this time is infinite or not (well known halting problem proven to be algorithmically undecidable). So, this is even theoretically...
15 May 2011 by Pong D. Panda
Take a look at this[^] and check if it will work on your side.
15 May 2011 by Mark Salsbery
When the exception gets thrown, drill down into the innerexception details - there's more info there!Either your service endpoint isn't using a BasicHttpBinding or your URL is wrong. I suspect the latter.Your code works fine for me.
16 May 2011 by Ramana Bellary
Hi, Can anyone tell me how to call a WCF service method by using Reflection in C#. I should not add WebReference or wcf service Dll at client side.Thanks & Regards,Ramana
22 May 2011 by Sergey Alexandrovich Kryukov
There is no difference what type of the property you use.Your mistake is Convert. (This class haunts CodeProject inquirers. How infected everyone with this abusing this type?) You probably fail to understand that all types inherit from System.Object, which is a parameter type of...
21 Aug 2011 by murtaza dhari
A generic dropdown control using LINQ to SQL and Entities using Reflection
30 Aug 2011 by Ilka Guigova
Sample use of generics and type retrieval