Thursday, April 12, 2012

c# interview question :- Why is stringbuilder concatenation more efficient than simple string concatenation?

This question is one of the favorites question which comes during c# interviews and the interviewer is not only expecting which one of them is more efficient. But he is also expecting the reason for the same.

In order to understand the same better lets consider the below scenario where we have two lines of code which does string concantenation.

For a simple string concantenation code shown below it will create 3 copies of string in memory.

//The below line of code Creates one copy of the string

string str ="anup";

/* The below line of code creates three copies of string object one for the concatenation at right hand side and the other for new value at the left hand side. The first old allocated memory is sent for garbage collection.*/

str = str + "anup";

When you use the string builder for concatenation it will create only one copy of the object.


/* The below code uses string builder and only one object is created as compared to normal string where we have 3 copies created*/

StringBuilder

objBuilder = new StringBuilder();

objBuilder.Append("anup");

Ok now summarizing what should we say to the interviewer.

String is immutable. Immutable means once assigned it can not be changed. Thats why it creates more copies of the object as it can not use the same instance.String builder is mutable , in other words the same object will changed rather than creating new objects.

So string builder is more efficient as compared to simple string concatenation.

Wednesday, April 4, 2012

Understanding Predicate Delegates in C#

Introduction

NET Framework 2.0 came with the concept of Predicate Delegates, but compared to the other features of .NET, it never got the attention it deserved. It is really a powerful concept which makes it easy to write searching algorithms on collections. These are also widely used while performing filter operations on WPF object data binding. In this article, we will take a look into the concepts behind predicate delegates and try and understand their importance.

What is a predicate delegate?

A predicate delegate is a delegate with the following signature:

Return type - bool
Argument type - generic
So, a predicate delegate is a delegate which points to a boolean function that returns true or false and takes a generic type as an argument. A predicate delegate thus is a delegate which is capable of taking any custom type as an argument. This makes it quite useful because what we get as a result is a generic delegate. The bool function that it points to has logic to evaluate any condition and return true/false accordingly.


Why use a predicate delegate?

The most common use of a predicate delegate is for searching items in a collection. Because a predicate delegate is a delegate of type T or generic, it is most useful when searching items in a generic collection. It really comes handy when you have a collection with tons of items and you need to perform a search operation. Using a predicate delegate not only reduces the lines of code that needs to be written, but also increases performance of the application. These are also used while performing filter operations on IcoolectionView objects while performing data binding in WPF.

For example, create a console application and declare an Employee class. Declare these properties for the Employee class: FirstName, LastName, and Designation. See code below:

class Employee
{
private string _firstName;
private string _lastName;
//private int _empCode;
private string _designation;

public Employee()
{ }
public Employee(string firstName, string lastName, string designation)
{
_firstName = firstName;
_lastName = lastName;
_designation = designation;
}
///
/// Property First Name
///
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
///
/// Property Last Name
///
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string Designation
{
get { return _designation; }
set { _designation = value; }
}
}

In the Main() method of the console application, declare three employees as below:
// Declare 3 employees
Employee emp1 = new Employee("Anshu", "Dutta", "SSE");
Employee emp2 = new Employee("John", "Doe", "Manager");
Employee emp3 = new Employee("Jane", "Doe", "Assistant");

Create a generic List and put the above employees in the list:

List empList = new List { emp1, emp2, emp3 };

We will demonstrate the use of a predicate delegate by performing a search operation on the Employee List.

Method #1 - The traditional way of doing it

Create a bool function that searches an employee first name and returns true if found:


private static bool EmpSearch(Employee emp)
{
if (emp.FirstName == "Anshu")
return true;
else
return false;
}
Declare a predicate delegate pointing to that function:

Predicate pred = new Predicate(EmpSearch);
Call the Find() method of the List<> and pass the predicate delegate as an argument:
Employee emp = empList.Find(pred);


The Find() method internally iterates through each item in the list and calls the function EmpSearch, passing each item from the list as an argument one by one. When the FirstName of the employee matches the condition, the function returns true. The Find method then returns that employee object to the Employee placeholder emp. That means for each item in the list, the Find() method calls the function EmpSearch passing the items as arguments one by one. Whichever item satisfies the condition in the function is then returned.

Print the result to check:

Console.WriteLine("Employee Found {0}",emp.FirstName);
Console.ReadLine();

c# - String to Generic [Type conversion]

public static T To(this string text)
{
return (T)Convert.ChangeType(text, typeof(T));
}

// sample usage
int val = "124".To();
double dbl = "124.5".To();