Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access private fields

Tags:

c#

.net

private

Is it possible to get or set private fields?

I want to get System.Guid.c. Is there a way to access it or should I just copy the code from the strut and make the fields public?

like image 409
godzcheater Avatar asked Jun 02 '12 13:06

godzcheater


People also ask

How do I access a private field?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.

What is a private field in Java?

In Summary private keyword in java allows most restrictive access to variables and methods and offer strongest form of Encapsulation. private members are not accessible outside the class and private method can not be overridden.

What are private fields?

Private fields are accessible on the class constructor from inside the class declaration itself. They are used for declaration of field names as well as for accessing a field's value. It is a syntax error to refer to # names from out of scope.


2 Answers

You can use reflection as suggested by Quantic Programming

var guid = Guid.NewGuid();
var field= typeof (Guid).GetField("_c", BindingFlags.NonPublic |BindingFlags.GetField | BindingFlags.Instance);
var value = field.GetValue(guid);

Although if you are okay with first converting the guid to a byte array, I might suggest:

var guid = Guid.NewGuid();
var c = BitConverter.ToInt16(guid.ToByteArray(), 6);

The latter approach avoids using reflection.

Edit

You mention needing to be able to set the value as well, you can still avoid reflection:

var guid = Guid.NewGuid();
var guidBytes = guid.ToByteArray();

// get value
var c = BitConverter.ToInt16(guidBytes, 6);

// set value
Buffer.BlockCopy(BitConverter.GetBytes(c), 0, guidBytes, 6, sizeof(Int16));
var modifiedGuid = new Guid(guidBytes);
like image 57
Chris Baxter Avatar answered Oct 04 '22 09:10

Chris Baxter


You should try System.Reflection. Here's an example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace AccessPrivateField
{
    class foo
    {
        public foo(string str)
        {
            this.str = str;
        }
        private string str;
        public string Get()
        {
            return this.str;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            foo bar = new foo("hello");
            Console.WriteLine(bar.Get());
            typeof(foo).GetField("str", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(bar, "changed");
            Console.WriteLine(bar.Get());
            //output:
            //hello
            //changed
        }
    }
}
like image 24
Mark Segal Avatar answered Oct 04 '22 09:10

Mark Segal