Home > OS >  What are the ways I can write this differently? - static bool M (int x) => x%2 == 0;
What are the ways I can write this differently? - static bool M (int x) => x%2 == 0;

Time:01-29

I'm currently studying for a test and I've looked up what Function, Action and Predicate mean and I know that only Action doesn't have a return value and Predicate returns a bool value which is what I need in my question. This is the code I got in the question:

static bool M (int x) => x%2 == 0;

These are the potential answers given:

A) Func <bool, int> A = M;

B) Func <int, bool> B = M;

C) Action <int, bool> C = M;

D) Predicate <int> D = M;

Based on what I've learned and some simple logic it should be B and D, right? Can someone confirm this for me?

CodePudding user response:

Let's ask the compiler:

compiled code

Clearly A) & C) are compiler errors. So, B) & C) are correct.

The Func<int, bool> delegate for B) looks like this:

public delegate TResult Func<in T, out TResult>(T arg);

And the Predicate<int> delegate for D) looks like this:

public delegate bool Predicate<in T>(T obj);

Both match the signature for M.

CodePudding user response:

You can call a static function by it's class. For example:

public class yourClass
{
> public static void DoSomething(bool isTrue)
> {
> //Here you can do some things
> }
}
yourClass.DoSomething(true);

if you want a function to return some value eg bool, string etc

Public class yourClass
{
>public static bool DoSomething(bool isTrue)
>{
>>if(isTrue)
>>{
>>return false;
>>}
>>else
>>{
>>return true;
>>}
>}
}
bool isItTrue = yourClass.DoSomething(true);

A function that returns a value must always have a return value. If you remove the else-part from the example above, you will get an error that not all code returns a value.

  • Related