Reputation: 145
How to get instances of a class using C# Reflection?.
For example,
public class Sample
{
}
Sample s = new Sample();
Sample s2 = new Sample();
Sample s3 = new Sample();
How to get these three instances of sample class using reflection?
Upvotes: 1
Views: 4257
Reputation: 14860
Using System.Activator.CreateInstance
you can create instances of a class using reflection. For example...
System.Type type = typeof(Sample);
object obj = Activator.CreateInstance(type);
In this example obj
is your newly created instance. There's few overloads of this method, more information in this MSDN Documentation
If what you want is to be able to retrieve all instances of a class, I guess this is not possible using managed code. You will need to use unmanaged code to either profile the managed heap using the Profiling API or use the HeapWalk function to enumerating all objects allocated in the managed heap.
Upvotes: 1
Reputation: 12468
var s = (Sample)Activator.CreateInstance(Sample);
var s2 = (Sample)Activator.CreateInstance(Sample);
var s3 = (Sample)Activator.CreateInstance(Sample);
Upvotes: 0