Ramasamy Nagappan
Ramasamy Nagappan

Reputation: 145

How to get instances of a class using Reflection?

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

Answers (2)

Leo
Leo

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

Edit Based On Comment

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

shenku
shenku

Reputation: 12468

var s = (Sample)Activator.CreateInstance(Sample);
var s2 = (Sample)Activator.CreateInstance(Sample);
var s3 = (Sample)Activator.CreateInstance(Sample);

Upvotes: 0

Related Questions