Can C# extension methods access private variables?

C#Extension Methods

C# Problem Overview


Is it possible to access an object's private variables using an extension method?

C# Solutions


Solution 1 - C#

No. You can do the same in an extension method as in a "normal" static method in some utility class.

So this extension method

public static void SomeMethod(this string s)
{
	// do something with 's'
}

is equivalent to some static helper method like this (at least regarding what you can access):

public static void SomeStringMethod(string s)
{
	// do something with 's'
}

(Of course you could use some reflection in either method to access private members. But I guess that's not the point of this question.)

Solution 2 - C#

No it cannot.

However, you will be interested to know that the other answers are incorrect in saying that normal static methods cannot access private fields. A static method can access private non-static member fields in its own class. The following code is perfectly valid and shows a static method accessing a private field:

public class Foo
{
    private bool _field;

    public static bool GetField(Foo foo)
    {
        return foo._field;
    }
}

Now... back to your question. You might think that an extension method should be able to do the same thing, given the (non-existent) "equivalence" to static methods that other answers claim exists. However, you cannot declare extension methods inside a nested class. So if you try to do the following:

public class Foo
{
    private bool _field;

    public static class Extensions
    {
        public static bool GetField(this Foo foo)
        {
            return foo._field;
        }
    }
}

You will get a compile error saying

> Extension method must be defined in a top level static class; Extensions is a nested class

Note that, interestingly enough, removing the this keyword causes the code to compile fine. The reasons for this are discussed here:

  1. https://stackoverflow.com/questions/3930335/why-are-extension-methods-only-allowed-in-non-nested-non-generic-static-class
  2. https://stackoverflow.com/questions/11443842/why-not-allow-extension-method-definition-in-nested-class/12037840#12037840

Solution 3 - C#

No:

public class Foo
{
    private string bar;
}

public static class FooExtensions
{
    public static void Test(this Foo foo)
    {
        // Compile error here: Foo.bar is inaccessible due to its protection level	
        var bar = foo.bar;
    }
}

Solution 4 - C#

Use Reflection

Not recommended, but you could possibly access any private variable of any type using another extension method like so:

public static T GetFieldValue<T>(this object obj, string name) {
    var field = obj.GetType().GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
    return (T)field?.GetValue(obj);
}

And then access a private field of an arbitrary type:

Foo foo = new Foo();
string privateBar = foo.GetFieldValue<string>("_bar");

Solution 5 - C#

No, unless you give some kind of access to them through public properties or a proxy pattern.

Solution 6 - C#

If you own the class that you are extending, you can always declare the class partial, then extend the class and have access to all the private members in a different file... But you wouldn't really be using extension methods.

Solution 7 - C#

An extension method is essentially a static method so all you have access to are the public members of the instance on which the extension method is invoked on

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeoView Question on Stackoverflow
Solution 1 - C#M4NView Answer on Stackoverflow
Solution 2 - C#Zaid MasudView Answer on Stackoverflow
Solution 3 - C#Darin DimitrovView Answer on Stackoverflow
Solution 4 - C#Bruno ZellView Answer on Stackoverflow
Solution 5 - C#Yuriy FaktorovichView Answer on Stackoverflow
Solution 6 - C#RimbimbamboView Answer on Stackoverflow
Solution 7 - C#Abhijeet PatelView Answer on Stackoverflow