Smit Modi
Smit Modi

Reputation: 75

Calling a private function from another class in C#

I have a program called Scenario2_Client.xaml.cs that has the following function:

namespace SDKTemplate
{

    public sealed partial class Scenario2_Client : Page
    {
        private MainPage rootPage = MainPage.Current;
        // code

        // this is the function I would like to call
        private void RemoveValueChangedHandler() 
        {
            ValueChangedSubscribeToggle.Content = "Subscribe to value changes";
            if (subscribedForNotifications)
            {
                registeredCharacteristic.ValueChanged -= Characteristic_ValueChanged;
                registeredCharacteristic = null;
                subscribedForNotifications = false;
            }
        }
        // ...
    }
}

And then I have added a class in a different file (but in the same project) called EchoClient.cs which has the following code:

namespace SDKTemplate
{
     class EchoClient
     {
         public void TcpClient()
         {
             try
             {
                 TcpClient client = new TcpClient("139.169.63.130", 9999);
                 StreamReader reader = new StreamReader(client.GetStream());
                 StreamWriter writer = new StreamWriter(client.GetStream());
                 string s = string.Empty;
                 while (!s.Equals("Exit"))
                 {
                     Console.WriteLine("TCP Client connected....");
                     Console.WriteLine("Enter a string or number to send to the server: ");
                     s = Console.ReadLine();                    
                     writer.WriteLine(s);
                     writer.Flush();
                     string server_string = reader.ReadLine();
                     Console.WriteLine(server_string);
                 }

                 reader.Dispose();
                 writer.Dispose();
                 client.Dispose();

             }
             catch (Exception e)
             {
                 Console.WriteLine(e);
             }
         }
     }


    internal class Console
    {
        internal static string ReadLine()
        {
            throw new NotImplementedException();
        }

        internal static void WriteLine(string v)
        {
            throw new NotImplementedException();
        }

        internal static void WriteLine(Exception e)
        {
            throw new NotImplementedException();
        }


    internal class TcpClient
    {
        private string v1;
        private int v2;

        public TcpClient(string v1, int v2)
        {
            this.v1 = v1;
            this.v2 = v2;
        }

        internal void Dispose()
        {
            throw new NotImplementedException();
        }

        internal Stream GetStream()
        {
            throw new NotImplementedException();
        }
    }    
 }

Is there a way to call that function from this class?

I would have done something like this if it was public:

EchoClient client = new EchoClient()
client.somefunction();
client.somefunction();

..but since this method is private, how should I access it?

Upvotes: 0

Views: 7069

Answers (2)

Flydog57
Flydog57

Reputation: 7111

I'm not sure why @Codor was down-voted, but here's the same answer fleshed out a little more. First I create a class with a private method:

public class PrivateFunction
{
    private int _age;

    public PrivateFunction(int age)
    {
        _age = age;
    }

    private int DoSomethingPrivate(string parameter)
    {
        Debug.WriteLine($"Parameter: {parameter}, Age: {_age}");
        return _age;
    }
}

I created a method that takes parameters and returns an integer to show all possibilities.

Then I call it:

   var type = typeof(PrivateFunction);
   var func = type.GetMethod("DoSomethingPrivate", BindingFlags.Instance | BindingFlags.NonPublic);
   var obj = new PrivateFunction(12);
   var ret = func.Invoke(obj, new[] {"some parameter"});
   Debug.WriteLine($"Function returned {ret}");

and I get this in the output (proving something happened):

Parameter: some parameter, Age: 12
Function returned 12

If you are going to repeatedly call the same function (perhaps with different objects), save the MethodInfo object in func. It's immutable and re-useable.

Upvotes: 2

Codor
Codor

Reputation: 17605

It is possible to invoke a private method using reflection as follows.

var iMethod
  = client.GetType().GetMethod("somefunction",
                               BindingFlags.NonPublic | BindingFlags.Instance);
iMethod.Invoke(client, new object[]{});

Upvotes: 3

Related Questions