{"id":279,"date":"2023-07-07T09:33:00","date_gmt":"2023-07-07T08:33:00","guid":{"rendered":"https:\/\/ishooscode.com\/?p=279"},"modified":"2023-07-07T09:35:13","modified_gmt":"2023-07-07T08:35:13","slug":"access-private-member","status":"publish","type":"post","link":"https:\/\/ishooscode.com\/index.php\/2023\/07\/07\/access-private-member\/","title":{"rendered":"How to access private member of class"},"content":{"rendered":"\n<p>This article reflect on how to access private member of class. There are multiple routes to achieve this but in this article we will focus on the right approach.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction<\/h2>\n\n\n\n<p>Setting or getting private variable is quite a corner scenario while developing new application. Developers always find a work around to make the data available in private member to them. However, There is a more efficient and recommended mechanism to access private member. Here we can access the private variable using reflection and in built microsoft libraries.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Real-world scenario where access private member is required?<\/h2>\n\n\n\n<p>In real-world, it is possible that you never encounter such scenario where there is a need to access private variable. Nevertheless, If you do then you\u2019ll simply change access specifier for the member.<\/p>\n\n\n\n<p>In UTC or TDD development you might find yourself in scenario where you need to access or change the value of private variable of a class. In UTCs we often do such things to re-create negative scenario. We might need to access private variable of a third-party variable to generate desirable result.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How can we access private member of class?<\/h2>\n\n\n\n<p>Quite simple, you just need to do some R&amp;D with reflection classes and need to spend some time with <strong>Type<\/strong> class provided in .net .<\/p>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using System;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\n\r\nnamespace CrossProjectDemo\r\n{\r\n    public class Car : IEnumerable\r\n    {\r\n        private string name = string.Empty;\r\n        private string prvtVariable = \"PrivateVariable\";\r\n\r\n        public string Name {\r\n            get { return name; }\r\n            set { name = value; }\r\n        }\r\n\r\n    }\r\n}<\/code><\/pre>\n\n\n\n<p>As you can see, here are two private variables,<\/p>\n\n\n\n<ol>\n<li>name<\/li>\n\n\n\n<li>prvtVariable&nbsp;<\/li>\n<\/ol>\n\n\n\n<p>While name is being accessed in a public Property Name, prvtVariable will be accessed directly<\/p>\n\n\n\n<p><em>Let\u2019s see how,<\/em><\/p>\n\n\n\n<p>First in your application import Reflection<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using System.Reflection;<\/code><\/pre>\n\n\n\n<p>Then follow the code,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Car c = new Car();\nType typ = typeof(Car);\nFieldInfo type = typ.GetField(\"prvtVariable\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\nvar value = type.GetValue(c);<\/code><\/pre>\n\n\n\n<p>C#Copy<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/f4n3x6c5.stackpathcdn.com\/UploadFile\/BlogImages\/10102019094545AM\/PrivateVarGet.PNG\" alt=\"Access private member\"\/><\/figure>\n\n\n\n<p>In the above image, you can see the type.IsPrivate is true which means the variable is private,<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/f4n3x6c5.stackpathcdn.com\/UploadFile\/BlogImages\/10102019094545AM\/PrivateVarGet1.png\" alt=\"\"\/><\/figure>\n\n\n\n<p>And we can access its value into the value variable.<\/p>\n\n\n\n<p>That\u2019s easy right.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Write to private member<\/h2>\n\n\n\n<p>Now, Let\u2019s move towards how we can change its value. Lets\u2019 make few changes to the existing code<\/p>\n\n\n\n<p>Just add one-line right after Getvalue() method call,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var value = type.GetValue(c);\ntype.SetValue(c, \"Not so much\");<\/code><\/pre>\n\n\n\n<p>and now you have changed the value of a private variable,<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/f4n3x6c5.stackpathcdn.com\/UploadFile\/BlogImages\/10102019094545AM\/PrivateVarset.PNG\" alt=\"\"\/><\/figure>\n\n\n\n<p>Easy, isn\u2019t it. So here we\u2019re accessing private variables through reflection.<\/p>\n\n\n\n<p>For details on reflection visit microsoft learner site <a href=\"https:\/\/learn.microsoft.com\/en-us\/dotnet\/csharp\/advanced-topics\/reflection-and-attributes\/\" title=\"here\">here<\/a>. Cheers!!!<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">More posts like this<\/h4>\n\n\n<ul class=\"wp-block-latest-posts__list wp-block-latest-posts\"><li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/ishooscode.com\/index.php\/2023\/12\/13\/introduction-to-azure-cosmos-db\/\">Introduction to Azure Cosmos DB<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/ishooscode.com\/index.php\/2023\/09\/02\/enhancing-app-security-with-azure-managed-identities\/\">Enhancing app security with Azure Managed Identities<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/ishooscode.com\/index.php\/2023\/08\/23\/comparing-performance-of-lists\/\">IL code performance of Generic List And Non Generic List<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/ishooscode.com\/index.php\/2023\/07\/30\/how-does-a-dictionary-maintains-data\/\">How does a dictionary maintains data<\/a><\/li>\n<li><a class=\"wp-block-latest-posts__post-title\" href=\"https:\/\/ishooscode.com\/index.php\/2023\/07\/12\/enumerator-or-foreach\/\">What is better between Enumerator or foreach<\/a><\/li>\n<\/ul>","protected":false},"excerpt":{"rendered":"<p>This article reflect on how to access private member of class. There are multiple routes&#8230;<\/p>\n","protected":false},"author":1,"featured_media":281,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[22,59],"tags":[20,15,60],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts\/279"}],"collection":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/comments?post=279"}],"version-history":[{"count":2,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts\/279\/revisions"}],"predecessor-version":[{"id":308,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts\/279\/revisions\/308"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/media\/281"}],"wp:attachment":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/media?parent=279"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/categories?post=279"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/tags?post=279"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}