I made a very simple program of Delegates. I have no idea why is it showing error, even though I compared it with the one given in MSDN library, its same like the one in MSDN, still not getting compiled..the error says- "The name 'Add' does not exist in the current context "and same for the other method.. Subtract. Please help me find what is the problem..
namespace DelegatePrac
{
public delegate void One(int a, int b);
public class Some
{
static void Add(int a, int b)
{
int c = a + b; Console.WriteLine("{0}",c);
}
static void Subtract(int a, int b)
{ int c = a - b; Console.WriteLine("{0}",c);
}
}
class Program
{
static void Main(string[] args)
{
One o1,o2;
o1 = Add;//gives error here
开发者_开发知识库 o2 = Subtract;//and here!!
o1(33,44);
o2(45, 15);
Console.ReadLine();
}
}
}
I was following this link- http://msdn.microsoft.com/en-us/library/ms173175.aspx
Thanks
You should see a compiler message:
The name 'Add' does not exist in the current context
which tells you that it has no clue which Add
method you are talking about; Add
is a static method in Some
- so you need:
o1 = Some.Add;
o2 = Some.Subtract;
static methods aren't globally available; you can access static methods from the current type (and from base-types) via just their name, but if it is an unrelated type you need to qualify it with the declaring-type.
At this point it will give you a compiler error:
'DelegatePrac.Some.Add(int, int)' is inaccessible due to its protection level
which hints that it is a private method; so add public
(or internal
) to them:
public static void Add(int a, int b) {...}
Have you tried exchanging those two lines with errors with this?
o1 = Some.Add;
o2 = Some.Subtract;
You haven't posted your error, but the class Program has no Add
or Subtract
methods, so I guess your error is that Add
and Subtract
is not found.
EDIT
And as ssd said in his answer, the static methods have to be public
to be accessed from outside the class. You have not specified any access modifier, and thereby the methods will default to private
.
Two things:
- You need to mark
Add
andSubtract
aspublic
. - They are not part of
class Program
. So while using them in other classes thanSome
, you need to specify they are part ofSome
by usingSome.Add
andSome.Subtract
.
Corrected Code:
namespace DelegatePrac
{
public delegate void One(int a, int b);
public class Some
{
public static void Add(int a, int b)
{
int c = a + b; Console.WriteLine("{0}",c);
}
public static void Subtract(int a, int b)
{
int c = a - b; Console.WriteLine("{0}",c);
}
}
class Program
{
static void Main(string[] args)
{
One o1,o2;
o1 = Some.Add;//gives error here
o2 = Some.Subtract;//and here!!
o1(33,44);
o2(45, 15);
Console.ReadLine();
}
}
}
精彩评论