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

1 Mar 2024 by Dev Leader
In this article, I’ll provide you with 4 simple code examples illustrating how reflection works in C#.
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...
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...
1 Oct 2023 by hans.sch
Silly me. In my question, I said that this line causes the exception: auto ret = method->Invoke(m_pWorker, arg_dummy/*arglist*/); Further, I said that m_pWorker was declared as Object^. This, of course, wasn't true. Actually, the declaration was...
13 Sep 2023 by Maxim Kartavenkov
I think you miss something around m_pWorker and the method also specify the nullptr or create an empty instance of the array arg_dummy here is an example which will be useful - I made it with just C# but the reflection methods which you should...
12 Sep 2023 by hans.sch
I'm trying to call a method of a class that was defined in a C# assembly. The calling code is C++/CLI. Problem: I keep getting a System.Reflection.TargetException with message "Object does not match target type." The assembly has one public...
12 Sep 2023 by Phil J Pearson
Why are you passing a parameter (arg_dummy) to a method that takes no parameters?!
18 Aug 2023 by Maxim Kartavenkov
had you try the next way: int MyCallback(int i) {} public delegate int IntCallback(int i); IntCallback^ callback = gcnew IntCallback(MyCallback); // Use callback variable as an argument
17 Aug 2023 by hans.sch
I'm playing with C++/CLI and calling into a .NET assembly. There is no specific use case, I simply want to learn. I wrote the assembly in C#. It exports a class with a few methods, and a delegate type which is used in one of the methods:...
6 Feb 2023 by JBartlau
This article provides an overview of Visual Studio's integration of combit's report generator List & Label.
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...
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...
20 Sep 2022 by Mateen Khan
I have a winforms application which was working fine. Recently i formatted my system and reinstalled VS 2008. From that time the application has stopped running.When i run it through VS it gives error"exception has been thrown by the target of an invocation."I went on to debug and...
20 Sep 2022 by Member 15773989
for the said error, we are talking about inner exception. How to get this inner exception? running bat "${NUGET_HOME}/nuget.exe restore Dotsolution.sln from jenkins file and getting this error: Error parsing solution file at...
14 Jul 2022 by Jaume González
Solution using reflection to dynamically load and execute C# code in a workflow context
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...
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...
15 Jun 2022 by Richard MacCutchan
I think you will find that these calls will only work on an actual object of a generated class. At compile time the T prefix does not have a value, it is just a marker for the compiler. See Class (Java Platform SE 8 )[^] for the available options.
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.
4 Nov 2021 by #realJSOP
A tool to generate model and viewmodel classes directly from your selected database
29 Sep 2021 by benji_dv
How to clear all events is quite simple. It needs a finger of reflection...
15 Aug 2021 by Vlad Neculai Vizitiu
A discussion of "init" keyword introduced in C# 9
8 Jul 2021 by Member 13798091
fun main(){ val crewCrewCrew = listOf( Sloths("Jerry", false,15), Panda("Tegan"), Manatees("Manny")) crewCrewCrew.forEach { mammalFactCheck(it, Mammal::vertebraeCount) mammalFactCheck(it,...
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...
3 Jul 2021 by Member 13798091
sealed class Genre{ sealed class Fiction : Genre(){ object Classics: Fiction() object Fantasy: Fiction() object ScienceFiction: Fiction() } sealed class NonFiction: Genre(){ object Biography: NonFiction() object Business:...
3 Jul 2021 by Richard MacCutchan
See javaClass - Kotlin Programming Language[^]. And simpleName - Kotlin Programming Language[^].
21 Jun 2021 by Shivprasad koirala
Understanding two terminologies - reflection and dynamic keyword
20 Oct 2020 by Oshtri Deka
In your case obj is instance of MyClass and value is list you wish to pass. var obj = new MyClass(); var newValue = new List(); fieldInfo.SetValue(obj, newValue ); Read more about it.
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...
8 Sep 2020 by TabZhang
Thanks Richard! I find use interface is a better way. dll and MainProgram both can reference the Interface. Interface Code: using System; namespace MyInterface { public interface ITestAction { string FailReason { get; set; } ...
8 Sep 2020 by TabZhang
dll name is "RefTest.dll",code as below: using System; namespace RefTest { public class Test { public event Action OnMessage; public void WriteString() { Console.WriteLine("Write String"); ...
7 Sep 2020 by Richard Deeming
The MS documentation already covers this: How to: Hook Up a Delegate Using Reflection | Microsoft Docs[^] Assembly assembly = Assembly.LoadFrom("RefTest.dll"); Type typeClass = assembly.GetType("RefTest.Test"); object obj =...
18 Jul 2020 by Member 14779968
I have 3 projects under my solution. One of them is the main base project where I want to have the json file "Testdata.json". I have to use this file across all 3 projects.. How can I get the path dynamically without hard coding it, and avoid...
17 Jul 2020 by OriginalGriff
Provide a public static method in one of the assemblies which retrieves the JSON path (or even the JSON data itself as a string) and returns it. Provided the project is referenced by the other two, they can call it.
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...
10 Jun 2020 by Member 14779968
Currently in my class DataEntries I have to sub class, UserObjects and TagObjects. I am trying to access the properties of TagObjects in my test class.. I have another class where these objects are serialized which is DataProvider class. I am...
5 May 2020 by honey the codewitch
This tip shows you a robust way to get the type of items a collection can hold. It works with non-generic collections too.
7 Jan 2020 by honey the codewitch
Solve some common resource complications in .NET with this simple utility class
3 Jan 2020 by Member 12947047
These are the two tables CompositeDTO,CompositeKeyDTO. Using reflection I want to save into database. The database structure is:CREATE TABLE public.test_jdbc_composite ( id uuid NOT NULL, num character varying(50) NOT NULL, title character varying(150), date_add timestamp without time...
18 Aug 2019 by rohitsies
CSV file generator using simplistic approach
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...
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 phil.o
Since Tuple have a lot of definitions, each with a different number of generic arguments, I don't think there is a magic solution (except the one you are using) to get whether an instance is a tuple or not. Problem is typeof(Tuple) will only match Tuple, the singleton version.
23 Jul 2019 by #realJSOP
This doesn't work? if (val is Tuple)
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: [^].
23 Jun 2019 by VDima77
Hi, I have following simple interface public interface IWrite { void SaveToFile(string path); } public class A :IWrite { [CustomSerialize('some value')] public B B1 {get;set} [CustomSerialize('some value')] public C C1 {get;set} } public class B :IWrite{ } public class C :IWrite{ } ...
23 Jun 2019 by #realJSOP
Instead of invoking the get method., why don't you just get the property's .Value?
28 May 2019 by Gerry Schmitz
obj = info.GetValue(obj, null); At this point, you call GetPropValue() to get the "nested class properties"; insuring, of course, you only "dive down" 1 extra level in this case. How you supply your target properties for the nested class is another matter: 2 lists / strings?
28 May 2019 by istudent
I have nested class which has two properties. I need to get value of one the of the nested class along with main class. foreach (var row in reportRowList) { var k = row; List dataRow = new List(); ...
2 May 2019 by Valerii Tereshchenko
Objects Comparer framework provides mechanism to recursively compare complex objects by properties (supports arrays, lists, different types of dynamic objects and more), allows to override comparison rules for specific properties and types.
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...
10 Jul 2018 by Graeme_Grant
You don't need to use reflection with MEF, you simply Export & Import to share data - the data can exist in a DLL/EXE outside of the main app. So long as MEF can compose, the data will be visible. This is what we did in another MEF Solution[^] where reflection was requested for a plugin system...
10 Jul 2018 by JohnMeers
I have an application using MEF and am trying to write integration tests for the Plug-ins. The code I have is:- public string Run() { IFunction IUT = null; string Wanted = "NewUser"; foreach (Lazy func in...
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...
4 Jul 2018 by johannesnestler
Have a look at MEF - it may is exactly what you need... Managed Extensibility Framework (MEF) | Microsoft Docs[^]
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.
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 =...
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...
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...
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).
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...
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 =...
25 Feb 2018 by Frederic GIRARDIN
Hi. Creating a .NET DataSet is easy with Visual Studio, but there is no way to expose that object from a shared DLL. Indeed, when we use only one EXE, we have the same problem: dynamically changing the Dataset ConnectionString which is only a parameter does not seem natural: we traffic a value...
25 Feb 2018 by Frederic GIRARDIN
The fact is that I misunderstood the TableAdapterManager, so I tried to work directly with the table adapter. To do this, I operated a wide replacement of Friend to Public. An operation that was required after each change of the DataSet Designer! And of course, I was wrong. Last Friday, I found...
18 Dec 2017 by Gaurav Chinchankar
Whenever my supporting COM dll's is called through reflection technique in C#, It gives me "Exception has been thrown by the target of an invocation." My Code: public class ExecuteAssembly { IAssembly objIAssembly = new Xml_Operations.XmlRetrive(); public void StartExecution() { ...
20 Nov 2017 by Prabhu S M
dll file containing the method, Project file that calls the method in dll, exception and my findings are below, I do not understand what I'm missing. Please help!dll file:public class Class2 { public string TestMethod1() { return "hello world!"; ...
15 Nov 2017 by JoeManJoe
Hello. I have a need to show my images with reflection in an mvc application. I want this to be cross- browser. I have looked at a number of examples but I found only one that came close. The image is that of one of several employees which will change on record selection change. So it has to be...
15 Nov 2017 by Richard Deeming
Remove the background image from the CSS, and set it via an inline style: .gf-icon-huge { position: relative; width: 141px; height: 141px; background-repeat: no-repeat; /* Added to make the image fill the available space */ background-size: cover; background-position: center...
26 Sep 2017 by Nicolas Kogler
This article will take a look at the benefits of code generators, the .NET reflection and external files to reduce code maintenance in industries with a lot of data.
10 Sep 2017 by TabZhang
Dear I am quite new for C#,I'm looking for help with the following questions. I am Plan to build one adaptable test platform with C# to achieve the following features,it just like NI-Teststand, but quite support .Net Only. This is dummy Test Tree, Each Step will use Reflection Call .Net...
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.
10 Sep 2017 by Graeme_Grant
XML is not the most efficient at passing data between two processes. Rather than specifying only one way of doing this, here is a Google Search that will give you a few different solutions: c# passing between processes - Google Search[^]
19 Aug 2017 by Graeme_Grant
Expanding on Mehdi Gholam's solution, here is a real-life example of where the method ProcessFileType "discovers" the type of data that it needs to convert to, looks up the type of data, then executes the conversion from JSON string and returns a class structure of a specific type. // only some...
19 Aug 2017 by MYQueries1
I am using the Invoke method to call method using reflection. Performance of this not great. Is there any other solution What I have tried: void ExecuteMethodViaReflection(TestObj comm) { var paramNames = comm.paramNames; //of type string array var paramData = comm.Data; //of type...
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...
15 Aug 2017 by Vaibhav M Nalwad
Resolving Dependencies via Attributes and Reflection
21 Jul 2017 by The_Unknown_Member
Why I need to use Type.GetType() when I make new instance of Type ? Instead of this: Type T = Type.GetType("CSharp_Practicing.Customer"); Why I can't just do this ? Type T = Customer; What I have tried: Asking question here in CodeProject.com
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...
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...
20 Jul 2017 by OriginalGriff
Because Customer does not derive from Type - and you can't create a new instance of a class just by using the class name. You can do this: Type T = typeof(Customer); And that will do the same as using GetType. GetType is normally used for getting a Type based on a string based name at runtime,...
12 Jun 2017 by Paul D. Sheriff
The right way to use Reflection
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...
4 Jun 2017 by Puresharper
It may be easier and cleaner to wrap IQueryable provided by DbContext.Set() instead of produce a string to parse by compiler. Indeed you can take advantage by using expression tree and not required Codedom.
2 Jun 2017 by toomanydoubts.
I know that we cannot create an object of an interface . Annotation e = new Annotation () ; // compile time error . But I am confused about what happens in the following code . Class c = ob.getClass() ; // ob is an object of a class created by us . ...
7 Apr 2017 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 methods and constructors.
1 Apr 2017 by Bjørn
How to automatically initialize a class for an inherited class instance
23 Mar 2017 by Ralf Meier
My Situation is that I want to have a Delegate to a method from a Control.For that I use the code as follows : Private RepeatDelayCounter As Integer = 0 Private RepeatControl As Control = Nothing Private Delegate Sub delegate_OnClick(instance As Control, e As...
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() ...
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.
6 Mar 2017 by Sabyasachi Mukherjee
I need to design a class where each of the properties of the class is added and updated in an ObservableDictionary.Here is the code I have come up with. class Win32_DiskDrive : INotifyPropertyChanged { private readonly string _classname = "Win32_DiskDrive"; ...
5 Mar 2017 by DotNetSteve
Creating an extension class for View Models to save public properties using Generics and Delegates, replacing a reflection implementation
27 Feb 2017 by n.podbielski
If you want to optimize code, which is based on Reflection, delegates may be the thing you are looking for.
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.
22 Dec 2016 by UareBugged
Good day, I need to make function that will iterate on Dictionary that stores variable name and variable`s new value. After that, I need to update class variable with that value. void UpdateValues(Type type, Dictionary values) { foreach (var value in...
15 Dec 2016 by matt warren
Why is Reflection slow?
6 Dec 2016 by gaurav.s23
I decompiled the one dll and exported to Project/Solution.I tried to understand lines of codes but i could not understand following lines.Type type;object objectValue = RuntimeHelpers.GetObjectValue(type.GetField("processInfo", BindingFlags.IgnoreCase | BindingFlags.Instance |...
6 Dec 2016 by Richard Deeming
The code seems to be using private reflection[^] to read a value that's already exposed via a public property:Process.ProcessName Property (System.Diagnostics)[^]It's roughly equivalent to:strFrom = Process.GetCurrentProcess().ProcessName;Logger.write("process: " + strFrom);