call a protected method on an instance of a class in csharp

To call a protected method on an instance of a class in C#, you need to create a derived class that inherits from the base class that declares the protected method. You can then create an instance of the derived class and call the protected method on that instance.

Here's an example code snippet that demonstrates how to do this:

main.cs
public class MyBaseClass
{
    protected void MyProtectedMethod()
    {
        Console.WriteLine("This is a protected method.");
    }
}

public class MyDerivedClass : MyBaseClass
{
    public void CallProtectedMethod()
    {
        MyProtectedMethod(); // call the protected method
    }
}

public class Program
{
    static void Main(string[] args)
    {
        MyDerivedClass myDerivedObject = new MyDerivedClass();
        myDerivedObject.CallProtectedMethod(); // output: "This is a protected method."
    }
}
518 chars
25 lines

In this example, MyBaseClass declares a protected method called MyProtectedMethod(). MyDerivedClass is a derived class that inherits from MyBaseClass and defines a public method called CallProtectedMethod() that calls MyProtectedMethod() on the derived object. Finally, in the Main() method of the Program class, we create an instance of MyDerivedClass and call the CallProtectedMethod() method to output the message "This is a protected method.".

gistlibby LogSnag