Saturday, December 31, 2011

Difference between Equal method and Equal to operator (==))

Equality comparison in C# is of two different kinds:-

1)       Value equality and
2)       reference equality

1) Value equality normally compares two objects by value.  

For ex:-

val1 and val2 are two integer variables having equal value as 10.

int val1 = 10;
int val2 = 10;
Console.WriteLine(val1.Equals(val2));
Console.WriteLine(val1 == val2);
Console.ReadLine();

Output
--------
True
True

Because the value equality is based on object values, the Output using the Equal method and Equal operator (==) is True.

2) Reference equality compares two objects by reference and not by value.

If there are two objects obj1 and obj2 which are referring to the obj3, then the reference equality will return true.

For ex:-

I have create a sample class
public class Test
{
   public Test()
   { }
}

Herein creating an object of Test class.
Test objTest = new Test();

Example 1:-

Now two different objects objT and objT1 is created which are referring to the objTest object.
Object objT = objTest;
Object objT1 = objTest;

Console.WriteLine(objT.Equals(objT1));
Console.WriteLine(objT == objT1);
Console.ReadLine();

Output
--------
True
True

Example 2:-

In this example, two different objects objT and objT1 are created of the Test class.

Object objOne = new Test();
Object objTwo = new Test();

Console.WriteLine(objOne.Equals(objTwo));
Console.WriteLine(objOne == objTwo);

Output
--------
False
False

objOne and objTwo are two objects of the same class Test but they are not pointing or referring to the same object, that’s the reason the reference equality will return False for reference comparison.


Happy Coding.......

Saturday, December 17, 2011

Converting multiple rows of a single column into single row


COALESCE (Transact-SQL):-

 MSDN definition:- Returns the first nonnull expression among its arguments.

 Syntax

COALESCE ( expression [ ,...n ] )

ISNULL and COALESCE though equivalent, can behave differently. An expression involving ISNULL with non-null parameters is considered to be NOT NULL, while expressions involving COALESCE with non-null parameters is considered to be NULL.

In today's example, we will be finding a way to convert mutliple rows of a single column into a delimited string value.

For example my sample table (tblEmployee) data in SQL Server is as follows (in tabular format):-

ID
Name
Department
Age

1
John Smith
Software
32
2
Steve Smith
Finance
35
3
Pradeep Pavaluru
Marketing Division
29

4
John Leo
Software
40

I want to combine all the names for the given employee records as a delimited string. For achieving the same i will be using COALESCE function.


declare @ReturnName varchar(max)

Select@ReturnName= COALESCE(@ReturnName + ',', '')+[Employee Name]

fromtblEmployee

print 'Employees Name= '''+@ReturnName+''''

Output:
Employees Name= 'John Smith,Steve Smith,Pradeep Pavaluru,John Leo'

Happy Coding.....