Click here to Skip to main content
15,881,516 members
Articles / Programming Languages / C#
Tip/Trick

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 6.9K   2   1






Introduction



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()
    {
        Console.WriteLine(variable);
    }
}




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");
test.outp();


I hope you found this article interesting and useful.Thank you for attention.



License

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


Written By
Ukraine Ukraine
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 1 Never change a private member using ... Pin
SledgeHammer0119-May-10 5:12
SledgeHammer0119-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.