Anup Shah on WPF and Silverlight (Programming Garden)

IT 's For You!!!

Thursday, April 12, 2012

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

12:25 PM

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#

3:02 PM
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]

1:53 PM
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();

Monday, March 26, 2012

Q: What is XBAP?

4:32 PM

XBAP stands for XAML Browser Application. XBAP allows for WPF applications to be used inside a browser. The .NET framework is required to be installed on the client system. Hosted applications run in a partial trust sandbox environment. They are not given full access to the computer's resources and not all of WPF functionality is available.
WPF supports the creation of applications that run directly in a web browser. (So will WPF/E, when it is released.) They are called XAML Browser Applications (XBAPs), and have a .xbap file extension.
The power of this WPF support is that the exact same programming model is used for a XAML Browser Application as for a standard Windows application. Therefore, creating an XBAP isn’t much different than creating a standard Windows application. The main differences are as follows:
. Not all features in WPF or the .NET Framework are accessible (by default).
. Navigation is integrated into the browser (for Internet Explorer 7 or later).
. Deployment is handled differently.

Q: What are possible ways to implement distributed applications in .NET?

4:32 PM

.NET Remoting and ASP.NET Web Services.

Thursday, March 15, 2012

Q: Where’s the entry point in WPF application?

12:28 PM

When you create a WPF Windows Application in Visual Studio, the generated project has no Main method, yet it still runs as expected! In fact, even attempting to add a Main method
gives a compilation error telling you that it is already defined.
Application is special-cased when it is compiled from XAML, because Visual Studio assigns
the XAML file a Build Action of ApplicationDefinition. This causes a Main method to be
autogenerated.

Q: What unit of measurement is used by WPF?

12:27 PM
All absolute measurements, such as the numbers used in this section’s size-related properties,
are specified in device-independent pixels. These “logical pixels” are meant to represent
1/96th of an inch, regardless of the screen’s DPI setting. Note that device-independent
pixels are always specified as double values, so they can be fractional.
The exact measurement of 1/96th of an inch isn’t important, although it was chosen
because on a typical 96 DPI display, one device-independent pixel is identical to one physical
pixel. Of course, the notion of a true “inch” depends on the physical display device. If an
application draws a one-inch line on my laptop screen, that line will certainly be longer than
one inch if I hook up my laptop to a projector!