Thursday, November 20, 2008

Difference between ref and out parameter in C#

Both the ref and out parameters are basically used to return values with the same variables that is passed as an argument to a method. But the difference is that the variable passed as an out parameter need not be initialized and is exclusively used for returning data to the caller whereas a variable passed as a ref parameter should be initialized and is used to pass as well as receive data from the method.
Eg:
For Passing by reference
static void Main(string[] args)
{
int i, j; //Should be initialized
i = 3;
j = 4;
PassByRef(ref i, ref j);
Console.WriteLine(i);
Console.WriteLine(j);
}
static void PassByRef(ref int var1, ref int var2)
{
var1 += 3;
var2 += 4;
}
Output is i=6, j=8
For Passing as Out
static void Main(string[] args)
{
int i, j; //Need not be initialized
PassByOut(out i, out j);
Console.WriteLine(i);
Console.WriteLine(j);
}
static void PassByOut(out int var1, out int var2)
{
var1 = 10;
var2 = 20;
}
Output is i=10, j=20

Monday, November 3, 2008

Using LINQ and Lambda expressions in Compact Framework 3.5

I tried adding a reference to System.Linq in my class but was not able to find the reference and was aghast at this. Then I found that to add a reference to System.Linq, first we should add a reference to the System.Core.dll using the Add Reference option. Then add
using System.Linq;
in the class file.
I had a requirement to filter out an array based on certain conditions , populate a struct and then bind the data to a list view.
Consider a simple example where I have an array with different Temperature Zones such as Hot, Cold and want to sum all the temperatures in hot and cold and display.
My Array[0].TempZone = "hot";
MyArray[0].Temperature = 30;
My Array[1].TempZone = "hot";
MyArray[1].Temperature = 40;
My Array[2].TempZone = "Cold";
MyArray[2].Temperature = 40;
My Array[3].TempZone = "Cold";
MyArray[3].Temperature = 50;
In this case, only 2 rows should be displayed in the list view with TempZone as Hot and Temperature as 30 + 40 = 70 and second row with TempZone as Cold and Temperature as 40 + 50 = 90.
I have a struct to fill in from the array
Struct MyStruct
{
String tempZone;
Int finalTemp;
}
To achieve this I used a simple LINQ query
var hotlist = from item in MyArray where item.TempZone == "hot" select item;
var coldlist = from item in MyArray where item.TempZone == "Cold" select item;
And then used Lambda expressions to obtain the sum as
lMystruct = new MyStruct[2];
lMystruct[0].TempZone = "hot";
lMystruct[0].Temperature = hotlist.Sum(hot => hot.Temperature);
lMystruct[1].TempZone = "Cold";
lMystruct[1].Temperature = coldlist.Sum(cold => cold.Temperature);
which is pretty simple and the struct can now be bound to a listview.
There may or may not be more than row with hot or cold and not necessarily in the same order in which case .Net code becomes pretty complex.