Click here to Skip to main content
15,946,158 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am a new learner of c#. I want to find a number is odd or not using delegate anonymous function. I am getting the the above error. Where am i going wrong?

What I have tried:

public delegate bool oddOREvenDelegate(int s);
    class Program
    {
        static void Main(string[] args)
        {
            ///create object for class clsOdd_Even
            ///call the method "CheckisOdd" using the object
            ///display the result
            oddOREvenDelegate t = new oddOREvenDelegate(clsOdd_Even.CheckisOdd);

            Console.WriteLine(t(5));
            Console.Read();


        }
    }


    class clsOdd_Even
    {
        
        public static bool CheckisOdd(int s)
        {
            oddOREvenDelegate t = delegate (int s)
              {
                  if x => x % 2 == 0//cannot convert lambda expression to type bool
                    return false;
              };
        }
        
}
    }
Posted
Updated 11-Dec-17 22:31pm

You can also do shorter:
C#
public static bool CheckisOdd(int s)
{
   return ((s % 2) != 0);
}

or quicker:
C#
public static bool CheckisOdd(int s)
{
   return ((s & 1) == 1);
}
 
Share this answer
 
You do not need to create delegate twice:


public static bool CheckisOdd(int s)
{

	if (s % 2 == 0)
	{
 	     return false;
	}
	else
	{
	      return true;
	}


}
 
Share this answer
 
v2
C#
public static void Main (string[] args)
		{
			//define a delegate that takes an int and returns a bool
			Predicate<int> CheckIsOdd=i=>i%2!=0;
			//call the delegate and write the result
			Console.WriteLine(CheckIsOdd(5));
			//An alternative approach using an anonymous function
			PrintBoolValue (5,i => i % 2 != 0);
		}
		public static void PrintBoolValue(int i,Predicate<int> checkBool)
		{
			Console.WriteLine(checkBool(i));
		}
 
Share this answer
 

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