Friday, August 27, 2010

Static Concept (Shared in VB)

Static Concept
The static modifier can be used with fields, properties, methods, events, constructors, operators and classes. You can not use static modifier with destructors, indexers and types other than classes.
A type or a constant declaration is implicitly static, so that any type defined in class directly accessed by class name.

public class MyBaseC
    {
        public struct MyStruct
        {
            public static int x = 100;
        }
    }

Console.WriteLine(MyBaseC.MyStruct.x); 


Static class
Static class is a class that contains all static members and neither be instantiated nor inherited.
Members of the static class called by the name of class.
Making a class with all static members and a private constructor is same as creating a static class, because a private constructor protects a class to be instantiated.
Terminology
1. Can’t be instantiated.
2. Can’t be inherited.
3. Can contain only static members.
4. Sealed by default, they can not inherit from any class except Object class.
5. Can’t contain instance constructor, can contain static constructor.
Ex.

class myClass
        {
            public class myStaticClass
            {
                public static int Age;
                public static void Display(int x)
                {
                    //Method implementation
                }
            }
            public static void main()
            {
                myStaticClass.Age = 30;
                myStaticClass.Display(55);
            }
        }

Static members
Static members of a class are accessible directly by the name of class, can’t be accessed by instances.
A Static member is shared member for all the instances of class and accessed only by the name of class, only one copy exist of a static member.
Can be used to count no. of instances created or to stores some value that is shared b/w all instances.

Terminology

1. Static methods / properties can’t access other non-static members.
2. Static methods can be overloaded and can’t be overridden because they belong to class not to instance.
3. Constants can’t be declared static, because they are by default static.
4. C# does not support static local variables (variables that are declared in method scope).

Example - For employees of a company, if a class gives Name and address info of company then class should be static because these things are common for all employees.
static class CompanyInfo
{
public static string GetCompanyName() { return "CompanyName"; }
public static string GetCompanyAddress() { return "CompanyAddress"; }
//...
}
class Math is a static class.

Saturday, August 7, 2010

Generics


Note - Please ignore all the single quotes, put for some technical reason.

A generics is class, method, interface or structure that have place holder for types parameter.
A generic class has type parameter for its fields, methods’ parameters.
A method has type parameter for return type or one of its formal parameters.

Storing value / reference type or different data types in a single list(collection) achievable with ‘ArrayList’.

ArrayList lst1 = new ArrayList();

Lst1.add(10);
Lst1.add(150);
Lst1.add(“Red”);
Lst1.add(“Blue”);

But it comes at a cost of type conversion and not type safe also.
Every time when we add a value type to the list, boxing needed and when we retrieve it from list, unboxing needed, all it done implicitly.

Generics introduced with framework 2.0 that can achieve it without type conversion and also type safe.

Below given class definition can be used with any data type.


Class Myclass <’T’>
{

}

Myclass’<int> mycInt =new Myclass ‘<int>’ ();

Myclass’<'string'> mycStr =new Myclass’<'string'>’();

Namespace System.Collection.Generic provides some collection classes those support Generics.
Like Queue, Stake, List, Linked list etc.

Benefit : Code re-usability, type safe, no type casting required and efficient.

Terminology

1. Generic type definitions are templates you can’t instantiate the template, you must specify type at the time of instantiation.
2. Generic type parameters are place holders for types.
3. When we create instance of generic type definition, we specify type and the instance called ‘constructed type’ or ‘constructed generic type’.
4. General term generic type contains both ‘generic type definition’(template) and ‘generic constructed type’(instance).
5. A generic method has two parameter lists one is generic type and another is formal type.
T MyMethod1(T t) //Not a generic method
{
T temp = t;
Return temp;
}

A generic method must has its own generic types list.

T MyMethod2 <’T’> (T t) //Generic method
{
T temp = t;
Return temp;
}

Class myClass <’T’> //Generic Class
{
T MyMethod1(T t)
{
T temp = t;
Return temp;
}
}

Example : By stake examples we will try to understand benefit of Generics

For integers you can implement and use the IntStack:

public class IntStack
{
int[] m_Items;
public void Push(int item){...}
public int Pop(){...}
}

IntStack stack = new IntStack();
stack.Push(1);
int number = stack.Pop();

For strings you would implement the StringStack:

public class StringStack
{
string[] m_Items;
public void Push(string item){...}
public string Pop(){...}
}

StringStack stack = new StringStack();
stack.Push("Ram");
string name = stack.Pop();

//Using Generics we can make above approach with code reusability

public class Stack'<'T'>'
{
T[] m_Items;
public void Push(T item)
{...}

public T Pop()
{...}

}

Stack'<'int'>' stack = new Stack'<'int'>'(); //Integer stack

stack.Push(1);
stack.Push(2);
int number = stack.Pop();

Stack'<'string'>' stack = new Stack'<'string'>'(); //String stack

stack.Push("Ram");
stack.Push("Shyam");
string name = stack.Pop();

A generic class is declared without a specific type applied to it in the definition. Rather, the type is specified at the time the object is used.

Q. How Generics are type-safe?
Ans. A Generic type is a template, we specify type at the time of instantiation then you can add or assign items of only specified type to that instance, can't be added any type other than specified type, if you attempt to add any other type code will not compile .
===================
Ex.
public class Lineclass<'T'>:Page
{
public T LineMethod<'T'>(T t)
{
T Temp = t; return Temp;
}
internal string convt<'T'>(T Tnt)
{
T temp = Tnt; return temp.ToString();
}
public void main()
{
Lineclass<'double'> lc = new Lineclass<'double'>();
Response.Write(lc.convt(lc.LineMethod(500.00)));
}
}

**************************************************************
Generics - Brief detail

Requirement of generics -
A. Eliminating Repetitive code blocks with different data type.
B. Performance issue.
C. Insuring type safety.
D. Making code efficient.

Multiple generic types -
A single type can define multiple generic-type parameters. consider the code block

public Class Node'<'K,T'>'
{

public K Key;
public T Item;
public Node'<'K,T'>' NextNode;

public Node()
{
Key = DEFAULT(K);
Item = DEFAULT(T);
NextNode = null;
}

public Node(K key, T item, Node'<'K,T'>' netxtNode)
{
Key = key;
Item = item;
Nextnode = nextNode;
}

}

public class LinkedList'<'K,T'>'
{
Node'<'K,T'>' mHead;
public LinkedList()
{
mHead = new Node'<'K,T'>'();
}

public void AddHead(K key, T item)
{
Node'<'K,T'>' newNode = new Node'<'K,T'>'(key, item, mHead.NextNode);
mHead.Nextnode = newNode;
}
}

using List = LinkedList'<'int,string'>';
Public class ListClient
{
Void Main()
{
List Node1 = List();
Node1.Addhead(5,"First Node");
}
}

Constraint - When you define generic type, you can define constraints also there to restrict client code to use type that constraints allows.
You can define one or more constraints on generic type definition.

Requirement of Constraints - Whenever we need to validate or compare an item of generic list, compiler must have some guarantee that used operator or method will be applicable (compatible) with any type argument supplied by client code, this can be achieved by constraints.

Constraint

Description

Where T : struct

Type argument must be value type and not nullable.

where T : class

Type argument must be reference type, it can be class, interface, array, delegate.

where T : new()

Type argument must have a parameter less public constructor. If you are using this constraints with other then it must specified at last.

where T :

Type argument must be given base type or derived from given base type.

where T :

Type argument must be given interface type or type that implemented given interface. Multiple interface constraints can also be defined. Supplied interface type can be generic type.

where T : U

Type argument must be type or derived type of type supplied for generic U



Inheritance with generics -
If you inheriting a generic class in a concrete class than you must specify constructed generic type at inheritance.
public class vehicle'<'T'>'
{
}
Public class Car : Vehicle'<'int'>'
{
}

If child class is a generic class then you can use type parameter of base class for child class
Public class Car'<'T'>' : Vehicle'<'T'>'
{
}

If base class having constraints for generic type than you must re specify constraints at inheritance.
public class Car'<'T'>' : vehicle'<'T'>' where T : new()
{
}

Ex.2
public class Bike'<'T'>' : vehicle'<'T'>' where T : struct
{
}

Generic methods -
A method can define generic type parameters, even if containing class not using generics at-all this method called Generic method.
A generic method has type parameter for one of its formal parameter and it's return type.

public class Bicycle
{
public T Drive'<'T'>'()
{
T t = null;
return t;
}

public T Drive'<'T'>'(T t, int a)
{
return t;
}

}

If you are overriding a method of base class you must re-specify generic parameters.
If virtual method having constraint than you must re-specify constraints also on overridden method.
you can't add more constraints on overridden method.

public void SomeMethod'<'T'>'(T t) where T : IComparable'<'T'>'
{...}

At calling of generic method you have to specify data type of generic parameter type.
Bicycle obj = new Bicycle();

obj.Drive(); //Compile time error
obj.Drive'<'int'>'(); //Ok

obj.Drive("hello", 3); //Ok
obj.Drive'<'string'>'("hello", 3); //Also ok

C# compiler is smart enough, so if one of the parameter of method is generic type then you can call method
without specifying data type for generic type parameter, compiler will determine data type automatically by using passed
value of parameter.
obj.Drive'<'string'>'("hello", 3);

Generic static methods -
public class Truck'<'T'>'
{
public static void Speed(T t)
{....}

public static T Speed'<'X'>'(T t, X x)
{....}

}

If a static method using generic type parameter of its class then we will call it like
Truck'<'int'>'.Speed();

If method is generic then we will call it like
Truck'<'string'>'.Speed'<'int'>'("speed measer", 50);

Delegates and Generics - A Delegate can also define generic parameters like methods.

public class Truck'<'T'>'
{
public delegate void MsgSpeed(T t); //Delegate within class
public void SpeedA(T t);
public void SpeedB'<'X'>'(X x)
{....}

}

Truck'<'int'>' trk = new'<'int'>'();
Truck'<'int'>'.MsgSpeed delk;
delk = trk.speedA;
delk(20);

public delegate void TrcSpeed'<'X'>'(X x); //Delegate declared outside class
TrcSpeed'<'string'>' delc;
delc = new TrcSpeed'<'string'>'(trk.SpeedB);
delc("Del trace");

Reflection and Generics - type of Type now can represent generic type.

LinkedList'<'int,string'>' list = new LinkedList'<'int,string'>'();

Type type1 = typeof(list); //Bounded types
Type type2 =list.GetType();

Type typeU1 = typeof(LinkedList'<','>'); //Unbounded types
for multiple generic types we use ",".

Thursday, August 5, 2010

Welcome to my blog

I heartily welcome you on my blog.
I’ll post here my learnings from .net technology.


Thanks.

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...