Click here to Skip to main content
15,305,613 members
Articles / Programming Languages / C#
Posted 19 May 2010

Tagged as


2 bookmarked

Set private value of class out of class

Rate me:
Please Sign up or sign in to vote.
1.00/5 (1 vote)
19 May 2010CPOL1 min read


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.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Ukraine Ukraine
No Biography provided

Comments and Discussions

GeneralReason for my vote of 1 Never change a private member using ... Pin
SledgeHammer0119-May-10 5:12
MemberSledgeHammer0119-May-10 5:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.