Feb 2, 2012
tcawus
Comments Off

Lambda expressions

Today, as i said yesterday, it`s time for lambda expressions :) The definition is as follows:
“A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as “goes to”. The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read ‘x goes to x times x.’ “.
Ok, enough theory, let’s look at the simplest example (in console application) :

// delegates are like functions, they have arguments and return type
// this delegate will add arguments and return result
delegate int Sum(int firstarg, int secondarg);
static void Main(string[] args)
{
// here we initialize this, like a usual object !! and determine what it
// will do; left side of '=>' operator specifies input parameters, right
// side the action, as you can see I am not operate on specific
// examples, I create only a prototype
Sum sum = (x, y) => x + y;
// below is specific example
Console.WriteLine(sum(10, 15));
Console.Read();
}

The output is of course: “25″.
We can also change delegate into a procedure with built-in WriteLine (procedure, in contrast to the function does not return a result):

delegate void sumAndMultiplyBy2(int firstarg, int secondarg);
static void Main(string[] args)
{
sumAndMultiplyBy2 sum = (x, y) =>
{
int output = x + y;
output *= 2;
Console.WriteLine(output);
};
sum(12, 13);
Console.Read();
}

Output: “50″ – (12+13) * 2 = 50
Of course the optimal way is to do it in 1 line, like before, but I wanted to show that they can also be complex expressions.

Now let’s try something more difficult.
In my opinion lambda expressions are most useful in complex data structures, like in dictionaries, arraylists etc.

static void Main(string[] args)
{
// let's say we have a dictionary of people - key is name and value is age,
// like in my previous post.
Dictionary dict = new Dictionary();
// add example data
dict.Add("Wright", 12);
dict.Add("Smith", 29);
dict.Add("Johnson", 57);
dict.Add("Anderson", 83);
// now try to get all older people - over 55 years
// standard approach
Console.WriteLine("Using standard approach with foreach:");
foreach (KeyValuePair pair in dict)
{
if (pair.Value > 55)
{
Console.WriteLine("{0} - {1}",
pair.Key,
pair.Value);
}
}
// with lambda expression
Console.WriteLine("Using lambda expression:");
// we want pair(name, age), where the age is over 50
// next convert to array and print result
Array array = dict.Where(pair => pair.Value > 50).ToArray();
foreach (KeyValuePair element in array)
Console.WriteLine(element);
Console.Read();
}

Output will be of course the same in both examples:
“Johnson – 57
Anderson – 83″
We can try other operations with different generics.

Feb 1, 2012
tcawus
Comments Off

Thread with multiple parameters

Hi, recently I coded some quite big database application, and discover a problem when was trying to pass multiple parameters to Thread class.
In .NET 2.0 approach we have to create a class(which will be a container for parameters we want to pass) like that:

class MyParameters
{
public string name;
public int age;
// ... and so on
}

So, we want to pass 2 parameters: string and integer, lets say for example that string is a name and integer is age.
Next, when creating Thread object, do something like that:


public static void createThread()
{
// create ParametrizedThreadStart object with necessary method
ParameterizedThreadStart pts = new ParameterizedThreadStart(doWork);
// create Thread with ParametrizedThreadStart
Thread newThread = new Thread(pts);
// make our class and assign values - "Smith" and 29
MyParameters p = new MyParameters();
p.name = "Smith";
p.age = 29;
// Thread start
newThread.Start(p);
}

public static void doWork(object data)
{
// print result – parameters we passed
// (converted from object class to MyParameters)
Console.WriteLine(“Hi, my name is “+((MyParameters)data).name+” and I`m +”+((MyParameters)data).age);
}

Output: “Hi, my name is Smith and I`m 29″.
We passed 2 parameters but in my opinion this is not the best way. We lost some time when writing that and what is most important … this code is looking terrible – too many lines in relation to what we want to achieve.

I think the best solution, available from .NET 3.5, is:

public static void createThread()
{
Thread newThread2 = new Thread(We_Are_Passing_That_In_Lambda_Expression => doWork("Smith", 30));
newThread2.Start();
}

public static void doWork(string name, int age)
{
Console.WriteLine(“Hi, my name is ” + name + ” and I`m ” + age);
}

Output: “Hi, my name is Smith and I`m 30″.
Many, many lines less and I think even novice programmer could guess what is happening in this code.
This:

We_Are_Passing_That_In_Lambda_Expression => doWork("Smith", 30)

is lambda expression, I will dedicate another post to describe that better.

Edit: here you have - http://tomaszwagner.blog.com/2012/02/02/lambda-expressions/

Feb 1, 2012
tcawus
Comments Off

Hi :-)

Hello, my name is Tomek Wagner. In my first post i will write something about me and what can you expect from this blog.
First of all, i`m Pole, so please forgive me my poor english :)
I`m studying IT at Poznan University of Technology and interested in programming, especially in .NET and Java.
But don`t expect only standard applications, i will try to write something about such technologies as: WPF, Silverlight, Windows Phone, Android, Maven and many other.
I will describe typical problems in software development and propose some solutions.
So … see you back soon :)