Click here to Skip to main content
15,900,378 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi been trying to access my greet method, from my Helper class, but it is inaccessible due to its protection level.

How can i get access to a method from another class in c#, or work my way around the proctection?

What I have tried:

using System;

namespace classes
{
    public class Helper
    {
        static void greet()
        {
            Console.WriteLine("Hello");
        }
    }
    
    
    class caller
    {
        private static void Main(string[] args)
        {
            var instance = new Helper();
            instance.greet();
        }
    }
}
Posted
Updated 30-May-20 8:30am

1 solution

Just declare the method as public:
C#
public static void greet()

More info on accessibility levels:
Accessibility Levels - C# Reference | Microsoft Docs[^]

Edit: re-reading your code carefully, when you define a method as static, you don't access it from an instance of the class, but from the class itself. So you have two choices:

Either you keep the method static, but modify your call accordingly:
C#
using System;

namespace classes
{
    public class Helper
    {
        public static void Greet()
        {
            Console.WriteLine("Hello");
        }
    }
    
    
    class Caller
    {
        private static void Main(string[] args)
        {
            Helper.Greet();
        }
    }
}
This is the most sensible way, since a) you do not use any instance variable in the method. b) This simplifies the usage of the method (you don't have to create an instance of the Helper class).

Or you make the method an instance method:
C#
using System;

namespace classes
{
    public class Helper
    {
        public void Greet()
        {
            Console.WriteLine("Hello");
        }
    }
    
    
    class Caller
    {
        private static void Main(string[] args)
        {
            var instance = new Helper();
            instance.Greet();
        }
    }
}

Note that I also corrected the case of class and method, according to C# common accepted casing rules.
 
Share this answer
 
v4
Comments
Maciej Los 31-May-20 14:11pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900