IT Blog

  • Blog
  • Technology
    • Technology
    • Architecture
    • CMS
    • CRM
    • Web
    • DotNET
    • Python
    • Database
    • BI
    • Program Language
  • Users
    • Login
    • Register
    • Forgot Password?
  • ENEN
    • 中文中文
    • ENEN
Experience IT
In a World of Technology, People Make the Difference.
  1. Home
  2. Technology
  3. DotNET
  4. Accessing private fields in C#

Accessing private fields in C#

2020-09-03 864 Views 0 Like 0 Comments

Based OO principles the private fields should not be accessd by anything outside of the object. However, for some reason we have to access the private fields, a good example is unit testing.

With dotnet reflection we could access any fields, members in an object. The accessibility is controled by BindingFlags, specify proper bindingFlags we can access all private fields in a class. To access the private fields in base class we need to add one more level of the type with BaseType.

Here is the extension method to get the value of a public and private field in an instance.

public static T GetFieldValue<T>(this object obj, string name)
{
	var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
	var field = obj.GetType().GetField(name, bindingFlags);
	if (field == null)
		field = obj.GetType().BaseType.GetField(name, bindingFlags); //father
	else if (field == null)
		field = obj.GetType().BaseType.BaseType.GetField(name, bindingFlags); //granpa
	else if (field == null)
		field = obj.GetType().BaseType.BaseType.BaseType.GetField(name, bindingFlags); //father of granpa

	return (T)field?.GetValue(obj);
}

Loading

error
fb-share-icon
Tweet
fb-share-icon
IT Team
Author: IT Team

Tags: Blog
Last updated:2020-09-03

IT Team

This person is lazy and left nothing

Like
< Previous
Next >

Comments

Cancel reply
Newest Hotspots Random
Newest Hotspots Random
Rich editor not working Making web page scroll down automatically Getting data from Dapper result All Unicode Chars How to keep and display contact form 7 data Common Regular Expressions
Start build from Team Explorer Symbols:Quotation Marks,Brackets Make up table definition with [yr-mth] columns and column list CSS Tricks Post tweets with Power Automate How to Change Windows Default Download Path
Categories
  • Architecture
  • BI
  • C#
  • CSS
  • Database
  • DotNET
  • Hosting
  • HTML
  • JavaScript
  • PHP
  • Program Language
  • Python
  • Security
  • SEO
  • Technology
  • Web
  • Wordpress

COPYRIGHT © 2021 Hostlike IT Blog. All rights reserved.

This site is supported by Hostlike.com