Click here to Skip to main content
15,890,123 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 Updated

Reflection 

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...
16 Dec 2014 by #realJSOP
Eliminate the tedium of generating model and viewmodel classes for your WPF projects, and save a butt-load of time in the process.
3 Nov 2015 by #realJSOP
This is an alternative for "Compareing Two Complex objects of same class"
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).
23 Jun 2019 by #realJSOP
Instead of invoking the get method., why don't you just get the property's .Value?
23 Jul 2019 by #realJSOP
This doesn't work? if (val is Tuple)
4 Nov 2021 by #realJSOP
A tool to generate model and viewmodel classes directly from your selected database
13 Aug 2012 by 3529255
I have a console application and two class libraries say (A and B). I have class "a" in A and class "b" in B.Obviously my entry poin of program will be the console application. In class "a",I am loading the type of "b" through reflection.Type type = null; type =...
16 Dec 2015 by _ProgProg_
Dear All,I am facing some silly problem about getting class type using its name stored in a string.Here is my Case:I have a HR project Consists of the Following: 1- HR.Core Class Library Project which contains my classes (Employee, Department, ....) 2- HR.Domain ..... ...
30 Mar 2016 by _ProgProg_
Dears,I am trying to get all classes in a solution that has two projects with no reference between them but i am only getting classes to the current startup project.Here is my case:* I have a 2 projects in one solution (ConsoleApplication2 - ConsoleApplication11).*...
14 Apr 2016 by _ProgProg_
Dears,I want to do some weird job which is: adding attributes dynamically to my model class without adding these attributes directly on each property in the model class.the whole story is:I have an MVC project using Code first with domain driven design so i have the following:Core...
7 Sep 2013 by abbaspirmoradi
Look at this link.maybe help you:http://bytes.com/topic/c-sharp/answers/545315-list-all-controls-inside-each-form[^]
2 Oct 2011 by Abhinav S
Use GetField() as shown here[^].
27 Jul 2012 by Abhinav S
You just can't do this (masterobj.GetType) and do a cast.You need to know the class name.If you just need to pass the object over to another method, an easier option for you is to use the object type directly.e.InputParameters.Add("masterobj", (object)Context.Items["masterdata"]);
2 Feb 2014 by Abhinav S
You have to give the approrpate flags to emit fields - e.g. http://msdn.microsoft.com/en-us/library/system.reflection.fieldattributes%28v=vs.110%29.aspx[^].
13 Feb 2015 by Abhinav S
Use reflection - Dynamically Invoke A Method, Given Strings with Method Name and Class Name[^].Here is another simple example - C# GetMethod[^].
8 Apr 2015 by Abhinav S
Try these tutorials / links -Reflection introduction[^]How to use reflection in Asp.Net[^]If you are looking at a sample of reflection used in ASP.Net web controls, try -Reflection and ASP.NET Web Controls[^]Using Reflection to Bind Business Objects to ASP.NET Form Controls[^]
20 May 2012 by abhinav_soni
This article provides alternative to Java's Proxy class with bytecode manipulation.
25 Nov 2013 by Adam Zgagacz
The following code makes the trick: private void test() { Type tDict = Type.GetType("System.Collections.Generic.Dictionary`2[System.Int32, System.String]").GetGenericTypeDefinition(); var tDict3 = tDict.MakeGenericType(typeof(string),...
8 Apr 2015 by Adhiraj Jaryal
How to use reflection in ASP.NET ?
27 Jul 2012 by aditya behara
I am developing a website in C# and ASP.netMy application demands of getting the class name from object name. For achieving this,I have used a session object. The snippet is as follows:Page1 .. (the one sending the session object)clsCountryMaster obj = new...
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...
16 Feb 2012 by aidin Tajadod
You can use this:object oform;oform = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("[namespace].[formname]");((Form)oform).Show();replace the namespace with your application/form namespace and [formname] with the name of your form.
24 Oct 2023 by aledeol
I'm trying to do a generic persist method using reflecion and MongoDB. The normal code is: public bool InsertParent(ParentDTO parent) { var collection = db.GetCollection(ParentCollectionName); var...
4 Jun 2017 by Alen Toma
Hi. I have a method that generate Entityframework include dynamiclly from an object and build string that look like this: "x=> x.Connectors , x=> x.BlockEntryFieldsGroup.Select(GhIm=> GhIm.BlockEntry_Field.Select(GhImcc=> GhImcc.BlockEntry_Value)) , x=> x.BlockEntryOffSet" and i would like...
20 Apr 2013 by ali_heidari_
hey !can someone help me to know how generate a .exe file from a c# program?i tried these codes , but its not succesfull AppDomain ad = AppDomain.CurrentDomain;System.Reflection.AssemblyName an = new System.Reflection.AssemblyName();an.Name =...
6 Nov 2012 by AllainLG
Hi, I can't figure out, how to use getDeclaredMethods() (reflection) if the user chooses the file from GUI.Something like this:Class inclass= Class.forName("ClassName");Method[] methods = inclass.getDeclaredMethods(); But I don't know "ClassName", I get it later.I'd like to get...
10 Nov 2012 by AllainLG
Hi,I'd like to get all the methods from a file (.text or .java), but I don't know the file's name yet (the user can choose it with jFileChooser). So I don't know the class's name. I have this code: import java.io.BufferedReader; import java.io.File; import...
15 Jun 2016 by Allen C. Copeland Jr
Grokking the CLI - Part 1: Meta Mayhem
16 Jun 2016 by Allen C. Copeland Jr
Grokking the CLI - Part 2: Meta Meanderings
13 Aug 2012 by Andreas Gieriet
I assume you did try it out and now you want a confirmation of your observation?As long as you don't need any information from your loaded type (like calling a method or a property, etc.), you don't need any references anywhere.But since in most cases you do need some information of that...
13 Aug 2012 by Andreas Gieriet
Now that I did try it out myself, I think I found the reason for your problem:you get fooled by Visual Studio.Visual Studio usually deploys (silently) all the project references to the build output folder of the given C# project. I.e. when you add in the main program project a reference to...
26 Jan 2012 by Andrew Rissing
Using expressions, you can achieve a faster result with less code.public static T New(){ Type t = typeof(T); Func method = Expression.Lambda>(Expression.Block(t, new Expression[] { Expression.New(t) })).Compile(); return method();}Furthermore, this can...
16 Jun 2015 by Andy Lanng
Hi,So, my code has been working ok. I have a state-safe workflow, which means that if the workflow engine stops and unloads, then it should be able to start back where I left it.There are some stages that perform some setup (such as subscribing to events for eg) which I need to make...
16 Jun 2015 by Andy Lanng
Solved - Man, this is a pain!You need to make sure that the base types for EVERYTHING you invoke is reference from a different library to the loaded assemblies. It only means re-shuffling half you code >_So: If your loading assembly is the base type assembly then...
8 Jul 2015 by Andy Lanng
You will need a shared reference such as an interface or abstract class. both of your assemblies should reference the shared object.The other option it to create three properties that return each of the List. You can use these types in both of your assemblies because you have a...
23 Aug 2015 by Andy Lanng
I hope I have this correct:They way you propose to do this is not a good idea, but there are ways to achieve the same end result that are a good idea.Take a look at this://Generic Factory (Reflection)//Specify the worker and the return typeList addresses =...
9 Dec 2013 by AngelBlueSky
Hello, I made an mdi program and I load dinamically some child form this way:Assembly newDll = Assembly.LoadFile("Child_01.exe");Type type = newDll.GetType("Child.Form1");Object obj = Activator.CreateInstance(type);Form child = (Form)Activator.CreateInstance(type);child.MdiParent...
1 Jan 2015 by Anton Kaminsky
Hi,I'm working on migrating a C# project to java.In the C# project I have a factory class holding a dictionary between Type, and a delegate which creates appropriate type.I expose a generic method:T Create()So the user can write:var someObject =...
23 Oct 2013 by Antony Linish
Hi,To get referenced assemblies frorm a specific type, you can try using the code below.(typeof(Item).Assembly).GetReferencedAssemblies()Thank you,
19 Nov 2012 by anulas
I have implemented the code for reading the active sessions using the reference Reading All Users Session and Get a list of all active sessions in ASP.NET.Private List getOnlineUsers(){ List activeSessions = new List(); object obj =...
10 Sep 2011 by Aoi Karasu
This does not compile for me:isReadOnly.SetValue(attribute, Video);This does compile but gives you incorrect behavior:isReadOnly.SetValue(attribute, Volume);Try it like this:public class MenuProp{ // ... class content ... public void ChangeReadOnlyTo(bool...
11 Aug 2013 by ARIA 5
I have an interface called IAuditable as follows:public interface IAuditable{ string AuditSummary { get; } string AuditDetails { get; } }And two generic method in AuditTrail class as follows:public T GetActualOldValue() where T :...
21 Jul 2016 by ArunRajendra
Check this link. Hope it gives you a clue.c# - How to get the type of T from a generic List - Stack Overflow[^]
26 Oct 2013 by ASP.NET Community
Reflection is one of the very nice features of .net, with Reflection one can take out lotsa information about the type. When I say type that means it
11 Oct 2013 by ASP.NET Community
Reflection is an important capability of the .NET framework and enables you to get information about objects at runtime. In this article, we will
11 Oct 2013 by ASP.NET Community
Reflection is the ability of the .NET framework to gather information (metadata) about assemblies, modules and types at runtime. It allows you also
9 Sep 2011 by ayad0net
Hi,Try to search in Google may be find it;this code get it form google may be help u------------------------class TestClass{ private bool isMyPropertyReadOnly; public bool IsMyPropertyReadOnly { get { return isMyPropertyReadOnly; } set {...
27 Nov 2014 by battech
I have 2 dll's . 1)AbInterface.dll which has interface "InterfaceStart" and a method start() inside the interface . There are many classes too inside this dll.2)AbClass.dll which has a class "AbClassStart" that implements "InterfaceStart" and does have a definition for Start() method in...
14 Sep 2015 by Benj55
Hi, Very simple question. I need to interpret a string name (extracted from a control name) as an existing array variable name. Here is the code I simplify to well understand// My array definitionstring[] _dev = { "DC", "192.168.1.1", "Quebec", "Standalone"};// The...
29 Sep 2021 by benji_dv
How to clear all events is quite simple. It needs a finger of reflection...
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.
30 Sep 2022 by bharath bhushan 2022
I have a jar file which contains only testcase.class files. I need to parse that and find all the classes defined in that jar file and need to generate one report. I tried to do it with the reflection concept in Java. Some how, when loading a...
9 Feb 2015 by Bhis
Various ways to sort list and compare results
24 Mar 2022 by Bill Menees
Use .NET's TypeToTypeInfoMarshaler to get a full .NET type with member information from an IDispatch-based COM object.
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 =...
13 Nov 2014 by BillWoodruff
The interesting challenge here is how to make this a generic method, but ensure that every List passed into it for manipulation implements a Property named 'Sno.The way that is done is with a method constraint based on an Interface:public interface ISno{ int Sno { set; get;...
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...
21 Jul 2017 by BillWoodruff
If you have an instance of a Class, you can call instance .GetType() on it. If you simply have a reference to a valid Type identifier ... it's name ... you can call 'typeof(name). using System; namespace Whatever { public class TypeFun1 { private string Name; public...
23 Jun 2019 by BillWoodruff
I do not understand why you think you need reflection here. You can serialize an instance of 'A, and that will include the instances of 'B, 'C: public Properties with both 'get and 'set can be serialized: [^].
20 Oct 2020 by BishnuKarki
Here is my scenario. I have a MyClass class and protected field _myAttempt which is a list. _myAttempt list class looks like below. From MyClassTest, how can i assign value to Daily using Reflection. I have tried following under...
1 Apr 2017 by Bjørn
How to automatically initialize a class for an inherited class instance
18 Jul 2014 by Bjørn
A custom Json state machine parser, viewer and serializer for Json data
14 Sep 2015 by bling
You aren't using introspection so this simplified statement will do:A variable's name is not select-able by another variable's value.This statement:textBox1.Text = str2.Trim()[2];... gives you the character at position 2 which - in this case - is the letter 'e'.If you were...
3 Jun 2011 by BobbyBlueEyes
I am struggling with calling a method with reflection...The method signature is as follows: (changed the actual names...)I have a interface called :public interface ICharacteristics { Score calculateScore(int ScorecardID, string UniqueID, ArrayList...
22 Jan 2013 by BobJanova
Simply caching PropertyInfo (or FieldInfo etc) objects in a hashtable of string -> property was fast enough for quite a reflection-heavy problem for me.
6 Oct 2015 by bora1891
Hi All,I have a project in MVC C# code-first.I want to pass type to my method.And my method needs to class to work.But I don't want to pass class I want dynamic.I don't know is it possible or not?Here is my codes;strimg item ="PERSON" // item is a parametric I give the table name...
2 Feb 2014 by Brendon Webber
After performing a Pivot in SQL I end up with a datasource with a few known columns and a variable amount of unknown (at design time) columns.I used the classic DataSet - DataTable solution, but started hitting OutOfMemory exceptions while processing the data (60,000 rows and 95...
16 Jul 2018 by canard29
Hi, I'd like to load a Usercontrol by reflection with the function "Show" in my interface like this : void Show(); The code for the interface and to load is OK. Any idea ? Thank you for your great support Additional question : I'd like to launch a function in the plugin. IView is...
16 Jul 2018 by canard29
The sample is working well and it's integrated in my app. I learnt a lot with your very good sample. I'm trying to solve 2 issues, not very related to MEF : - The userControl is displayed in the top left corner. I'd like to display it in the center of the ContentControl - If the usercontrol...
8 Apr 2011 by cechode
Saw this a while back; it's simpler (dirty and wrong but... ):public static T Get(Func getDelegate, bool DefaultTOnNull = false, T defaultVal = null) where T : class{ T result = null; try { result = getDelegate(); } catch...
22 Jan 2013 by CHill60
There are some useful suggestions in the answer to this post ...http://stackoverflow.com/questions/771524/how-slow-is-reflection[^]
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.
19 Jun 2012 by Clifford Nelson
Sometimes a very frustrating aspect of programming wanting to do something, and not being able to do it. Sealed classes can sometimes be in your way, and sometimes it is that a method in a control is not marked as virtual. You can use the New keyword to replace a method, but if the class is...
20 Jul 2017 by CPallini
Because they are different beasts. Acccording to the documentation[^]: Quote: Type is the root of the System.Reflection functionality and is the primary way to access metadata. Use the members of Type to get information about a type declaration, about the members of a type (such as the...
10 Sep 2017 by CPallini
Quote: it without create new instance to improve efficiency. Do you really think you need that? I strongly doubt you are going to observe a performance improvement.
6 Apr 2018 by csrss
Here is a Java code, which I have found on the net, to set field value using reflection: public static boolean setField(Object object, String fieldName, Object fieldValue) { Class clazz = object.getClass(); while (clazz != null) { try { Field field =...
20 Feb 2015 by D. Christian Ohle
ICorDebugILFrame https://msdn.microsoft.com/en-us/library/ms232990[^]
11 Apr 2018 by Daniel Leykauf
Hi, I have a contextmenustrip and want to bind each "Click" event from each ToolStripMenuItem to another target control that has also a "Click" event - i.e. another Button. Due to the dynamic control creation at runtime (of the target buttons) I have to subscript the source event from the...
11 Apr 2018 by Daniel Leykauf
Hi, I found this working solution on: c# - Is it possible to "steal" an event handler from one control and give it to another? - Stack Overflow[^] Private Shared Sub CopyEvents(ByVal source As Object, ByVal target As Object, ParamArray events As String()) Dim sourceType As Type =...
25 Jan 2012 by Dean Oliver
An alternative to Activator.CreateInstance
26 Jan 2012 by Dean Oliver
The final solution after much debate and optimization:public class DynamicInitializer { static readonly Dictionary> list = new Dictionary>(); public static T New() where T : class { return New(typeof...
2 Feb 2012 by Dean Oliver
How we can harness the power of MEF and extend it by way of generics.
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...
1 Mar 2024 by Dev Leader
In this article, I’ll provide you with 4 simple code examples illustrating how reflection works in C#.
29 Feb 2016 by Dipak Mandol
I want to get all control's ID from a page in another page.suppose two pages A.aspx and B.aspx. I want want fetch all controls from page B.aspx into A.aspx pagepublic partial clas PageA:System.Web.UI.Page{ //all serverside controls of PageB must be listed here.}public...
3 Mar 2016 by Dipak Mandol
PageA.aspx------------From PageA.aspx I'm fetching all controls from PageB.aspx and storing in database.Controls are stored in database like (Thank you for submitting txtName.Text)PageB.aspx-----------In PageB.aspx,while clicking on Submit button I want to fetch those controls...
2 Sep 2014 by DiponRoy
Let’s see how to make a simple model or Entity mapper using reflections in C#
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.
26 May 2014 by Dolinka Márk Gergely
First one of a series of tutorials about C# code reweacing using Mono.Cecil
5 Mar 2017 by DotNetSteve
Creating an extension class for View Models to save public properties using Generics and Delegates, replacing a reflection implementation
25 Jan 2012 by Dropmans
Hi, I am working on a GUI framework. The framework is a WPF executable that can load ‘modules’ (.NET assemblies) that belong to components. The framework can show views that are defined in a module. Each main project in the organization creates their own component. Each component is a VS...
27 Oct 2012 by dsagner
Hi everyone, I've got a small (I hope) yet interesting problem. I have got an assignment today at my university which causes me a headache by now. The job is to design a swing app which uses reflection to create an instance of a class called "Pravokutnik" (never mind the class name) which is a...
6 Oct 2015 by Duncan Edwards Jones
You want type to be of TEntity?public class LINQDynamic where TEntity: class { public static TEntity GetQueryResult(object pkKey,TEntity type, params object[] pkKeys) { //TODO}or a different known type?public...
6 Apr 2018 by E.F. Nijboer
No need to reinvent the wheel. You can use Apache commons lang3 for basic reflection utilities and use commons beanutils for more advanced scenarios, like accessing nested properties. See the links below. FieldUtils (Apache Commons Lang 3.7 API)[^] org.apache.commons.beanutils (Apache Commons...
12 Dec 2011 by Eduard Lu
Session variables might help. Here take a look at these links.http://msdn.microsoft.com/en-us/library/ms178581.aspx[^]http://www.coveryourasp.com/Session.asp[^]Regards,Eduard
12 Oct 2014 by EduChapow
Hello everyone,I'm want a "clone" my Model to ViewModel using reflection.But my reflection function cant be reflect Virtual Properties, someone can help me with this?The code below is my method to "clone" with reflection:public static D ConvertItem(O o) where...
21 Dec 2012 by Elegantly Wasted
Great said by Mateen Khan, you need to understand what is you controls default value..eg i'm using combobox in silverlight and i was trying to bind its selected indexas a default its selected index was -1but it was get nothing from the respective property ...I looked inside...