21

i saw a function can be define in javascript like

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

and can be called like

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 can i define a function in the same way in c#. if yes then just give a small snippet of above like function definition in c# please. thanks.

Community
  • 1
  • 1
Mou
  • 15,673
  • 43
  • 156
  • 275
  • As a sidenote (I keep saying this whenever it pops up), in C#, you'd typically speak of *methods*, not of functions. – stakx - no longer contributing Aug 14 '11 at 09:43
  • 3
    @stakx Strictly speaking, function is the correct terminology here. It's not a coincidence that `Func` is named `Func`. – Tim Lloyd Aug 14 '11 at 09:44
  • 1
    @chibacity: `Func` as a delegate type is appropriately named, as it represents the *idea* of a function. However, in the C# language, there are no functions. You'll only ever subscribe methods to the delegate (even if they're anonymous). The term "function" is simply not appropriate in the context of C#. – stakx - no longer contributing Aug 14 '11 at 09:51
  • @stakx I disagree, it's semantically useful terminology. It embeds the fact that there is a return value, and to be pure as in this example, has no side effects. The term "method" does not indicate this. – Tim Lloyd Aug 14 '11 at 09:55
  • @chibacity: I need to take a step back to explain. The reason I mentioned this bit of terminology advice in the first place was to get the OP to recognise a difference between the JavaScript and C# languages, and that it is almost always wrong to call methods "functions". But you are right: While C# as a language does not have functions (as a syntactic construct), I concede that the *concept*, or *idea*, of a function can still be represented, e.g. with the `Func` delegates. – stakx - no longer contributing Aug 14 '11 at 10:01
  • 1
    @stakx Agreed, I just originally assumed the OP already knows the basics of methods and functions in C# and JS. The term is unfortunately overloaded. – Tim Lloyd Aug 14 '11 at 10:04

2 Answers2

28

You can create 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 a "shortcut" to delegates (it made from delegates) and use:

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

for example:

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

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

Naor
  • 23,465
  • 48
  • 152
  • 268
  • why do I recieve "A field initializer cannot reference the non-static field, method, or property" error if I call square(5)? – paraJdox1 Dec 27 '20 at 08:05
26
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);

Any of the following more verbose forms is possible, too: (I'm using square as an example):

  • Func<double,double> square = x => { return x * x; };
    The expression is expanded to a statement block.

  • Func<double,double> square = (double x) => { return x * x; };
    Explicit parameter list instead of just one parameter with inferred type.

  • Func<double,double> square = delegate(double x) { return x * x; };
    This one uses the older "anonymous delegate" syntax instead of so-called "lambda expressions" (=>).

P.S.: int might not be an appropriate return type for a method such as factorial. The above examples are only supposed to demonstrate syntax, so modify them as necessary.

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268