Tuesday, October 19, 2010

Generics : Part 1

/*
* Note: Please replace "<" with ! and ">" with *
* Generics are Type safe means it gives warning at compile time only not at RunTime
*/
/*
* ================
* List!* generics
* ===============
*/
List !int* lstintCg = new List!int*();
lstintCg.Add(1);
List !string* lststrCg = new List!string*();
lststrCg.Add("1");
/*
* ================
* SortedList!* generics
* ===============
*/
SortedList !int, string* slst = new SortedList !int, string* ();
slst.Add(1, "Value_1");
/*
* ================
* Dictionary!* generics
* ===============
*/
Dictionary !int, string* dict = new Dictionary!int, string*();
dict.Add(26691, "bimlesh.singh@aexp.com");
foreach (KeyValuePair !int,string* kvp in dict)
{
Console.WriteLine("Key : {0}\n value :{1}",kvp.Key,kvp.Value );
}
Console.Read();

Monday, October 18, 2010

Collections:Part 3

/*
* BitArray Class is derived from the System.Collections.generics
* it supports AND,OR ,XOR Opertaions
* It is used for storing just boolean value.
* It doesn't have Add or remove method like any another Collections.
*/
BitArray btArray1 = new BitArray(3);
btArray1[0] = true;
btArray1[1] = false;
btArray1[2] = true;
BitArray btArray2 = new BitArray(3);
btArray2[0] = true;
btArray2[1] = false;
btArray2[2] = true;
/*
* Note : if you want to change the length of the Array just set its length propery.
* =========================
* Conditions 1
* ==============================
BitArray bitXOR = btArray1.Xor(btArray2);
foreach (object bit in bitXOR)
{
Console.WriteLine(bit.ToString());
}
* o/p: False,false,false
==============================
* Condition 2
======================================
BitArray bitXOR = btArray1.And (btArray2);
foreach (object bit in bitXOR)
{
Console.WriteLine(bit.ToString());
}
*o/p: True,false,True
*

BitArray bitXOR = btArray1.Or(btArray2);
foreach (object bit in bitXOR)
{
Console.WriteLine(bit.ToString());
}
* o/p: True,false,True
==============================
* Condition 3
======================================

BitArray bitXOR = btArray1.Not();
foreach (object bit in bitXOR)
{
Console.WriteLine(bit.ToString());
}
* o/p: false,true,false
*/
Console.Read();

Collections: Part 2

/*Note:
* For small Collection we generaly use ListDictionary
* For Large Collections we use HashTable
* The Best Part is to use HybridCollections it is the remedy of the above issues
*/

Hashtable hTable = new Hashtable();
hTable.Add("a",1);
hTable.Add("b", 2);
hTable.Add("c", 3);
/*
* In the above there will be no Ordering of Sequence.
* foreach (object hs in hTable.Values )
{
Console.WriteLine("Key Values are : {0}",hs.ToString());
* o/p=1,3,2
}
*/
SortedList slist = new SortedList();
slist.Add("a", 1);
slist.Add("c", 2);
slist.Add("b", 3);
/*
* Bydefault ordering is ascending
* you Can Sort by Key and Value both.
* foreach (object sls in slist.Values )
{
Console.WriteLine("Key Values are : {0}",sls.ToString());
* o/p=1,2,3
}
*/
/*==============================================================
*Note:CommonUtilClass and StringComparer Class
*==============================================================
*/
/*
* Hashtable and Sorted List are CaseInsensitive
* To make it Case Sensitive Use CollectionsUtil CollectionsUtil.CreateCaseInsensitiveHashtable();
* Use NameSpace :using System.Collections.Specialized;
* Note : In The below Case It will through an error.
* Since it is having Same Ket a & A.
*/

Hashtable hTable = CollectionsUtil.CreateCaseInsensitiveHashtable();

hTable.Add("a", 1);
hTable.Add("A", 2);
hTable.Add("c", 3);

/*
* For Making HashTable Invariant Culture u Should use below code.
*/
Hashtable hash = new Hashtable(StringComparer.InvariantCulture);
SortedList list = new SortedList(StringComparer.InvariantCulture);


Queue q = new Queue();
q.Enqueue("First");
q.Enqueue("Last");
//Console.WriteLine(q.Dequeue());
//O/p : First

Stack st = new Stack();
st.Push("1");
st.Push("6");
st.Push("2");
//Console.WriteLine(st.Peek());
//Console.WriteLine(st.Pop());
//O/p: 2
//O/p: 2

/*
* With NameValue Collection we can use same key Name for using multiple values.
*/
NameValueCollection nvc = new NameValueCollection();
nvc.Add("Same_key","Value_1");
nvc.Add("Same_key", "Value_2");

foreach (object obj in nvc.GetValues("Same_key"))
{
Console.WriteLine(obj);
//o/p: Value_1,Value_2
}
Console.Read();

Thursday, October 14, 2010

Collections: Part 1

/*
*Name Space Required using System.Collections;
*This is an example of Arraylist
*/
ArrayList objArrlst = new ArrayList();
string[] arr = { "ID: 1","Domain: BNFS"};
objArrlst.Add("Name: Bimlesh Singh");
objArrlst.AddRange(arr);
objArrlst.Insert(0, "EMP Detail");
/*method 1.
* This is a way of Iterating through a Arraylist.
* With the help of IEnumerator Interface's GetEnumerator method which returns a Interface IEnumerator.
*/

objArrlst.Add(1);

IEnumerator Ienum = objArrlst.GetEnumerator();
while (Ienum.MoveNext())
{
Console.WriteLine(Ienum.Current );
}
/*method 1.
* This is a way of Iterating through a Arraylist with the help of Foreach loop.
* if we use foreach (String objstr in objArrlst)below it will through a casting error.
*/

foreach (Object objstr in objArrlst)
{
Console.WriteLine(objstr);
}

objArrlst.Remove(1);
/*
* Comparer Class is used for in the ArrayList.Sort method to do the default sorting.
* It is the default implementation of the IComparer implementation
*/
objArrlst.Sort();
Console.Read();

Friday, October 8, 2010

Type of GLOBALIZATION CultureInfo Class & enum CultureTypes


Culture can be classified in 3 groups
1. Invariant Culture
2. Neutral Culture
3. Specific Culture


NEUTRAL vs. SPECIFIC:
Neutral Culture contains only Language not region or Country
e.g English (en), French (fr), and Spanish (sp).

Specific Culture contains detail of both Language and region.
e.g en-US(English in United States),es-US etc.

Note : For getting the Current Culture
CultureInfo cInfo = Thread.CurrentThread.CurrentCulture;
Console.WriteLine("Name {0}",cInfo.Name);

//O/P->en-US
Console.WriteLine("Display Name {0}", cInfo.DisplayName);
//O/P->English
Console.WriteLine("Native Name {0}", cInfo.NativeName);
//O/P->English
Console.WriteLine("TwoLetterISOLanguageName {0}", cInfo.TwoLetterISOLanguageName);
//O/P->en
Console.Read();

NOTE : CurrentUICulture must be set at the application’s startup

CultureInfo cInfo = Thread.CurrentThread.CurrentUICulture;
Result will be same like above.

The CurrentCulture can be manipulated at any time during execution. However, this is not the case
With the CurrentUICulture. To be used correctly, the CurrentUICulture must be set at the onset of the
application (ideally in the Main method) or in a form’s constructor. Failure to do so can result in unexpected behavior.


CultureTypes is a enumType & it is Used with the GetCultures() function.
e.g
CultureTypes.AllCultures;
CultureTypes.FrameworkCultures;
CultureTypes.NeutralCultures ;
CultureTypes.SpecificCultures;


Sample Code

foreach (CultureInfo UsersCulture in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
Console.WriteLine("Culture: " + UsersCulture.Name);
}
Console.Read();

Sample Example :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Windows.Forms;
using System.Threading;
namespace Globalization_Part1
{
/*
* Step 1. create a window applicatio.
* Add a comboBox and set its ID =cbCulture
* Add three labels set the ID and text of all the labels.
*/

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/*
* Fill the comboBox at Form intialization
*/

foreach (CultureInfo UsersCulture in CultureInfo.GetCultures(CultureTypes.SpecificCultures ))
{
cbCulture.Items.Add(UsersCulture);
}
Console.Read();
}

private void button1_Click(object sender, EventArgs e)
{
if (txtCurrency.Text == "")
{
MessageBox.Show("Please supply a numeric value to currency e.g 1000"); }
else
{
//select the comboBox selected value
object val = cbCulture.SelectedItem;
CultureInfo cinfo = new CultureInfo(val.ToString());
Thread.CurrentThread.CurrentCulture = cinfo;
double cuurency = Convert.ToDouble(txtCurrency.Text);
//Set the currecy and dateTime with CultureInfo class setting.
lblCurrency.Text=cuurency.ToString("C", cinfo);
lbldate.Text = DateTime.Now.ToString(cinfo);
txtCurrency.Text="";
}
}
}
}


Points to be Remembered.
1. For creating a custom culture you should have to use CultureAndInfoBuilder Class.

2. Different Culture has different sorting and comparision rules.
to make a consistent sorting and comparision u should have to use CultureInfo.InvariantCulture.

3. In Formatting o/p ToString() and dateTime() helps.

Thursday, October 7, 2010

Explicit Interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interface_Example
{
public interface IEditPicture
{
void Paint();

}
public interface IEditImage:IEditPicture
{
//This will hide the method of IEditPicture's
new void Paint();
}
public interface IDrawing : IEditPicture
{
//Bydefault this will hide the IEditPicture's Method
void Paint();
}

public class Studio : IEditImage,IDrawing
{
/*
* For Explicit declaration of Interface don't use any access modifier
* InterfaceName.methodName() will be written instead of writting direct method name
*/

//This is IEditImage Method
void IEditImage.Paint()
{
Console.WriteLine("Paint Method of {IEditImage}");
}

//This is IDrawing Method
void IDrawing.Paint()
{
Console.WriteLine("Paint Method of {IDrawing}");
}


//This is IEditPicture Method
void IEditPicture.Paint()
{
Console.WriteLine("Paint Method of {IEditPicture}");
}

//This is Class Method
public void Paint()
{
Console.WriteLine("Paint Method of Studio Class" );
}

}


class Program
{
static void Main(string[] args)
{
Studio sd = new Studio();
((IEditImage)sd).Paint();
((IDrawing)sd).Paint();
((IEditPicture)sd).Paint();
//This will call method of Studio Class
sd.Paint();
Console.Read();
}
}
}

Implicit Interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interface_Example
{
public interface IEditPicture
{
void Paint(string ID);

}
public interface IEditImage:IEditPicture
{
//This will hide the method of IEditPicture's
new void Paint(string ID);
}
public interface IDrawing : IEditPicture
{
//Bydefault this will hide the IEditPicture's Method
void Paint(string ID);
}

public class Studio : IEditImage,IDrawing
{

public void Paint(string ID)
{
Console.WriteLine("Paint Method of {0}",ID );
}

}

public class Bollywod :Studio
{
//This will use internally New keyword and hide the method of Studio Class.
public void Paint(string ID)
{
Console.WriteLine("Paint Method of {0}", ID);
}

}
class Program
{
static void Main(string[] args)
{
Studio sd = new Studio();

((IEditImage)sd).Paint("IEditImage");
((IDrawing)sd).Paint("IDrawing");
((IEditPicture)sd).Paint("IEditPicture");
//This will call method of Studio Class
sd.Paint("Class Studio");
Bollywod bd = new Bollywod();
//This will call method of Bollywod Class
bd.Paint("Bollywod");
Console.Read();
}
}
}

Wednesday, October 6, 2010

Reference Type Example

Notes on Refernce Type.
e.g Class, String, Array,Exception etc.
1. Conventionally, the term object refers to an instance of a reference type, whereas the term value refers to
an instance of a value type, but all instances of any type (reference type or value type) are also derived from type
object.

2. Reference of a object stores in Stack but Actual object stores on Heap
//Both the below references 'a' & 'b' will be stored on Stack
CLassA a;
ClassA b;

//Both the below object 'aa' & 'bb' will be stored on Heap.

ClassA aa=new ClassA();
ClassA bb=new ClassA();


IMMUTABLE vs MUTTABLE:
string name = "Bimlesh";
name += "Kumar";
name += "singh";
//In this scenerio 3 copy of name will be created and last one will be latest one.
//name="Bimlesh";
//name="Bimlesh Kumar";
//name="Bimlesh Kumar Singh";

//To avoid this use either StringBuiler or join/Concat/FormatString
Console.WriteLine(name);

StringBuilder sb = new StringBuilder("Bimlesh");
sb.Append("Singh");
Console.WriteLine(sb.ToString());
Console.Read();

Value Type Example

enum Tasks
{
Mr, Mrs, Miss
// Mr=5, Mrs, Miss=2
};
//IN the above case int value will be 0,1,2
//And in commented peace of code value will be 5,6,2

/*The enum type must be byte, sbyte, short,ushort, int, uint, long, or ulong.
**********
* if we will not give the type it will take bydefault as Int
* e.g
enum Tasks:long
{
Mr=500,
Mrs,
Miss

};
**********
*/


class Program
{
static void Main(string[] args)
{
//============================Value Type Classification================================
//1. Built in Type: e.g int16,int32,decimal,system.char,double,boolean,datetime etc.
//2. User Defined Types: Structure
//3. Enums
//Note: 1> All value type stores in stack it takes small memory
// 2> Uint32 for all positive whole numbers
// 3> String() is a method derived from Syste.object all value types are derived from the same base class.

//============example on built in Value Types===========================
// Nullable b ;
//OR
bool? b;
b = true;
//Has value checks for nullability
if (b.HasValue)
{
Console.WriteLine("B has Proper Value i.e {0} ", b);
}
else
{
Console.WriteLine("B is having Null Value");
}

//=========================Enumerations Example===================
Tasks tsk = Task.Mr;

Console.WriteLine("B has Proper Value i.e {0} ", tsk.ToString());
//O/p: Mr
Console.WriteLine("B has Proper Value i.e {0} ", i);
//O/P: 1
Console.Read();
}
}