Can you assign a function to a variable in C #?

I saw how a function can be defined in javascript like

var square = function(number) {return number * number};

and can be called as

square(2);

var factorial = function fac(n) {return n<3 ? n : n*fac(n-1)};
print(factorial(3));

C # code

MyDelegate writeMessage = delegate ()
                              {
                                  Console.WriteLine("I'm called");
                              };

so I need to know that I can define a function in the same way in C #. if yes, then just give a small snippet above as a function definition in C #, please. thank.

+9
source share
2 answers

You can create a delegate type declaration:

delegate int del(int number);

and then assign and use it:

   del square = delegate(int x)
    {
        return x * x;
    };

    int result= square (5);

Or, as said, you can use the "shortcut" for delegates (it is made by delegates) and use:

Func<[inputType], [outputType]> [methodName]= [inputValue]=>[returnValue]

eg:

Func<int, int> square = x=>x*x;
int result=square(5);

You also have two other shortcuts:
Func with no parameters: Func<int> p=()=>8;
Func with two parameters:Func<int,int,int> p=(a,b)=>a+b;

+13
source
Func<double,double> square = x => x * x;

// for recursion, the variable must be fully
// assigned before it can be used, therefore
// the dummy null assignment is needed:
Func<int,int> factorial = null;
factorial = n => n < 3 ? n : n * factorial(n-1);

: ( square):

  • Func<double,double> square = x => { return x * x; };
    .

  • Func<double,double> square = (double x) => { return x * x; };
    .

  • Func<double,double> square = delegate(double x) { return x * x; };
    " " "-" (=>).

PS: int , factorial. , , .

+17

All Articles