a developer's notes – a semi-technical web development BLOG

March 31, 2013

Action and Func delegates in .NET extension methods

Filed under: C# — Duy Nguyen @ 7:11 pm
Tags: , , , , ,

The Action delegate never returns a value.

// no params
Action printEmptyLine = () => Console.WriteLine();

// one param
Action printNumber = x => Console.WriteLine(x);

// two params
Action<int, int> printTwoNumbers = (x, y) =>
                 {
                     Console.WriteLine(x),
                     Console.WriteLine(y)
                 };

A Func delegate returns some sort of value.

// at minimum, you have to specify the return type
Func getTime = () => DateTime.Now; // returns a type DateTime

// two params. The last param is the return type.
Func<int, int> square = x => x * x; // takes an int, returns an int

// three params
Func<int, int, int> multiple = (x, y) => x * y; // takes an int, returns an int

Using the delegates, you can just invoke them like this:

// using Action delegates
printEmptyLine();
printNumber(3);
printTwoNumbers(5, 10);

//using Func delegates
DateTime now = getTime();

Now when you use extension methods, will understand what it needs.

For example:
whereFunc
So the above, you know the where method takes a Employee type and returns a bool.

A Linq Expression

//This is the same Func delegate but there is an Expression Type around it.
Expression<Func<int, int, int>> multipleExpression = (x, y) => x * y; // takes an int, returns an int

You can’t just invoke expressions. You’d have to turn them back into delegates to use. Like this:

Func<int, int, int>> multipleExpression = multipleExpression.Compile();

Expressions are mainly used for Linq to SQL. Func and Action delegates are used in Linq to Objects.

When using any extension method, if you see a parameter for a Func, Action, or Expression, they all accept lambda expressions.

Advertisements

January 24, 2012

Why is Main in a console app a Static method and why are its methods Static?

Filed under: C# — Duy Nguyen @ 8:47 am
Tags: , , , , , ,

http://stackoverflow.com/questions/1685692/c-sharp-console-application-static-methods
Here is a great explanation!

Member functions don’t have to be static; but if they are not static, that requires you to instantiate a Program object in order to call a member method.

With static methods:

public class Program
{
    public static void Main()
    {
        System.Console.WriteLine(Program.Foo());
    }

    public static string Foo()
    {
        return "Foo";
    }
}

Without static methods (in other words, requiring you to instantiate Program):

public class Program
{
    public static void Main()
    {
        System.Console.WriteLine(new Program().Foo());
    }

    public string Foo() // notice this is NOT static anymore
    {
        return "Foo";
    }
}

Main must be static because otherwise you’d have to tell the compiler how to instantiate the Program class, which may or may not be a trivial task.

Blog at WordPress.com.