Search this blog

You can search for all the topics in our blog using our google custom search now.

Search the blog

Loading
Showing posts with label Topic Generic. Show all posts
Showing posts with label Topic Generic. Show all posts

Sunday, May 23, 2010

Explaining Generics using WPF Example

1. Go to file, select new project and you will see a window like this:




2. Now select WPF Application and give the project name as "ShoppingExample" and then click on OK.

3. Now double-click on Window1.xaml and it will open a designer window for you. Go ahead and drop controls on this window and make it look like this:


4. Once you are done, just check out the XAML CODE, if you are familiar with asp.net, you will be so happy to see this. Everything you do here has a feel of developing web application.

5. If you are unable to find the xaml view of window1 then dont worry, i will help you find it.





6.Right click on the project in the solution explorer, go to Add-->Add New Item-->Select a class in the window and name it as ShoppingCartItem.cs.

7. We are going to do a simple shopping example where in the store manager can keep track of all the prices of items in his store.

8. So we every Item has a name and a price.
Lets write a class for ShoppingCartItem which will have two attributes called Name and Price.

namespace ShoppingExample
{
public class ShoppingCartItem
{
public string ItemName;
public double Price;

public ShoppingCartItem(string _Name,double _Price)
{
ItemName = _Name;
Price = _Price;

}

public override string ToString()
{
return ItemName+" Price is " + Price.ToString() + " Rupees Only";
}
}
}

9. This class has one constructor which initializes two variables ItemName and Price.The other method has been used to override the ToString() function from base class for our custom use.

Once you are done with this, you are almost there.

10. Now we are going to create a generics List to store a list of ShoppingCartItems Objects like this:

public List ItemsList = new List();

10. ItemsList will store list of Items like Item1,Item2,Item3.....etc which will has a (Name1,Price1),(Name2,Price2),.....etc.

11.Now Double Click on Window1.xaml.cs and open the file. In that file write the below method:-

private void Window_Loaded(object sender, RoutedEventArgs e)
{

lbItems.ItemsSource = ItemsList;

//lbItems is the ListBox Control dropped in window1 designer

}

12. This suggests that everytime the particular window loads, listbox control will be binded to ItemsList which we created before.

13. Allright everything is set, incase you are still confused about what are really to acheive then let me explain it to you.
This screen allows the user to enter the item name and price .User clicks on Add to cart and the item he entered in textboxes gets saved in the listbox below.
So to do this, we need to add first create a ShoppingCartItem and then add it to the Generic List ItemsList.Since the listbox is binded to our ItemsList, we just need to refresh the listbox everytime and item is added. Below is complete code for Windows1.xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace ShoppingExample
{
///
/// Interaction logic for Window1.xaml
///

public partial class Window1 : Window
{
public List ItemsList = new List();
public Window1()
{
InitializeComponent();
}



private void btnAdd_Click(object sender, RoutedEventArgs e)
{
ShoppingCartItem I = new ShoppingCartItem(txtName.Text, Convert.ToDouble(txtPrice.Text));
ItemsList.Add(I);
lbItems.Items.Refresh();
txtName.Clear();
txtPrice.Clear();


}

private void Window_Loaded(object sender, RoutedEventArgs e)
{

lbItems.ItemsSource = ItemsList;

}
}
}


10.Run the application(Press F5)











Free MCTS EXAM training tutorials on this website, soon will be launching video tutorials for all the same topics

Saturday, May 22, 2010

Generics V/S Non Generics

Why use Generics??
1.By using generics we can ensure appropriate use of types
2.Improves performance by reducing the need to cast.

Non Generic Classes

I will explain now how Non generic classes differ from Generic classes.

Let us now compare SortedList from Non generic classes and SortedList from Generic Class to understand how does generics actually ensure the appropriate use of types.Lets create a class called Company as follows:

public class Company
{
public SortedList EmpList = new SortedList();

public Company()
{
EmpList.Add("Sameer", 5000);
EmpList.Add("Sanjay", 2000);
EmpList.Add("Shraddha", 1000);



}


}

Am Creating a sorted list which stores "Names" and "Salary" as Key/Value Pair. So we add a few pairs into the sorted list. Lets create another class as follows:

class Program
{


static void Main(string[] args)
{

Company Acompany = new Company();

foreach (string salary in Acompany.EmpList.Values)
{
Console.WriteLine(salary);
/*If you check EmpList has "Salary" of type Int. Hence the above line will require to cast the Int Object to be converted to String Object.This code wont give you any error even if no explicit type casting is mentioned.This kind of conversion hits performance.And also in many cases you will get many errors while casting between different types*/

}
Console.ReadKey();




}
The Above class displays the salaries of employees using Non Generic Class.

USAGE OF GENERICS
Lets Create another class called CompanyGeneric, which uses a Generic Sorted List as follows:

public class CompanyGeneric
{
public SortedList BEmployeeList = new SortedList();

public CompanyGeneric()
{

BEmployeeList.Add("Sameer", 5000);
BEmployeeList.Add("Sanjay", 2000);
BEmployeeList.Add("Shraddha", 1000);

}

}

Now let me display the salaries of all the employees like i did with sorted list.

class Program
{


static void Main(string[] args)
{


CompanyGeneric BCompany = new CompanyGeneric();


foreach (string s in BCompany.BEmployeeList.Values)
{

Console.WriteLine(s);
/*Now when you try to execute this code, you will get an error saying "Cannot convert type int to string". This is how generics helps us in ensuring appropriate use of types and improving the system's performance by reducing the casting operation.If we didn't have an option of generics, our code will be more error prone and tedious.*/

}
Console.ReadKey();


You have to change the above code as follows to execute the program.

class Program
{


static void Main(string[] args)
{


CompanyGeneric BCompany = new CompanyGeneric();


foreach (int i in BCompany.BEmployeeList.Values)
{

Console.WriteLine(i);

}
Console.ReadKey();






}
}


I hope you understood the need of generics in development of an application.I know generics is a complex topic and it is very difficult to understand if you are especially a beginner.Try to run the above code and experience it yourself.Only then you will understand the exact usage of generics

If you have any questions
Mail me @ shaiksameer.cse@gmail.com.
I hope this has proven to be of some help to you.
Have Fun
Sameer Shaik

Free MCTS EXAM training tutorials on this website, soon will be launching video tutorials for all the same topics