Pixie
Pixie

Reputation: 67

Method defined in different class not found in program class using delegate

I have added the following class to my project

delegate int NumberChanger(int n);

namespace lesson02
{
    class Testdelegate
    {
        static int num = 10;
        public static int AddNum(int p)
        {
            num += p;
            return num;
        }

        public static int MultNum(int q)
        {
            num *= q;
            return num;
        }

        public static int getNum()
        {
            return num;
        }
    }    
}

And in my program class under the main method I am trying to create an object of the delegate and assign the method AddNum to it:

NumberChanger nc1 = new NumberChanger(AddNum);

But the AddNum method is not recognized in this class and I get the error message: CS0103 C# The name does not exist in the current context

Can anyone see what I'm doing wrong?

Upvotes: 1

Views: 88

Answers (1)

David
David

Reputation: 10708

You need to reference the class when making a reference to a static method in a different class. Thus, from (I presume) Program.Main, you should reference Testdelegate.AddNum. EDIT: This presumes you have a using lesson02; reference at the top of your file, or Program exists within the lesson02 or a nested namespace.

Alternatively, if you make multiple reference to static Testdelegate members, you can use a static using (as of C# 6):

using static lesson02.Testdelegate;

Upvotes: 3

Related Questions