Once time I need to now size of class instance in C# which was a container of user classes. It was enough for me to know size in bytes of all it's fields.In this article I will demonstrate power of System.Reflection and System.Type. Also I found it interesting that it is possible to change value of private fields out of class. So lets start.
Using the code
To get know size of class I need to get all of private fields. I had done it with such method as GetFields. This method take some flags as parameter . To get all private public and protected fields you need to combine such flags as BindingFlags.NonPublic | BindingFlags.Public . Method GetFields return array of FieldInfo classes.With its help we can get know if field is primitive or array or some class. If type of object is primitive we can use build-in method of Marshal class - SizeOf. It will return size in bytes of our object. If it occurred that object is array we will find size of each element of it and add it to final result.So this function will be recursive . There is also help method getType which return type of current object: Collection, Dictionary, Primitive, Array or other class.
Other thing I want to show you is how get access out of class to its private fields. I will demonstrate you how easy is it. So let we have next class.
public class SampleClass
private readonly string variable = "Hello";
public void outp()
Suppose we need to change variable value on "Hello World".Next code show how to do it.
SampleClass test = new SampleClass();
FieldInfo field = typeof(SampleClass).GetField(
"variable",BindingFlags.Instance | BindingFlags.NonPublic);
field.SetValue(test, "Hello World");
I hope you found this article interesting and useful.Thank you for attention.