Reputation:
i have created a class person which is having functions add,sub,mul and mytest where i am passing my delegate reference
and in static void main i want if
DateTime.Now.Hour<12
it should call add
if DateTime.Now.Hour<20 it should call sub
.
but i am getting error
'ad1' does not exist in current context
class person
{
public void add(int x,int y)
{
Console.WriteLine(x+y);
}
public void sub(int x,int y)
{
Console.WriteLine(x-y);
}
public void mul(int x,int y)
{
Console.WriteLine(x*y);
}
public void test(mydel ad1)
{
ad1(2, 3);
}
}
class Program
{
static void Main(string[] args)
{
person p = new person();
if(DateTime.Now.Hour<12)
{
mydel ad1 = p.add;
}
else if(DateTime.Now.Hour<20)
{
mydel ad1 = p.sub;
}
p.test(ad1);
}
}
Upvotes: 0
Views: 365
Reputation: 734
class person
{
public void add(int x, int y) => Console.WriteLine(x + y);
public void sub(int x, int y) => Console.WriteLine(x - y);
public void mul(int x, int y) => Console.WriteLine(x * y);
public void test(Action<int, int> ad1) => ad1(2, 3);
}
class Program
{
static void Main(string[] args)
{
person p = new person();
Action<int, int> action = (x, y) => {};
if (DateTime.Now.Hour < 12)
{
action = p.add;
}
else if (DateTime.Now.Hour < 20)
{
action = p.sub;
}
p.test(action);
}
}
Upvotes: 0
Reputation: 9365
ad1
is declared inside the if
block in the Main
method and doesn't exists outside the if
scope.
I don't think you need this variable at all just call directly from within the if
:
static void Main(string[] args)
{
person p = new person();
if(DateTime.Now.Hour<12)
{
p.test(p.add);
}
else if(DateTime.Now.Hour<20)
{
p.test(p.sub);
}
}
This will also ensure that when Hour
> 20 nothing will be called, and you won't get a null exception.
If you do however choose to use this variable, define it before the if
(and assign it with null
) and ensure it's not null
before you use it.
Upvotes: 0