Wednesday, November 24, 2010

User control Vs Custom control

User Control
The syntax you use to create a user control is similar to the syntax you use to create a Web Forms page (.aspx). The only difference is that a user control does not include the html, form and body elements since a Web Forms page hosts the user control.
Creating and adding user control to form at runtime
you can add an user control to application by right click on solution and click on 'add new item' option.
You can add an user control to page by adding a register tag to page at compile time.
'<%@ Register TagPrefix="tp" Src="~/WebUserControl.ascx" TagName="MyUC" %>'
Now you can use control on page like '<tp:MyUC ID ="myFirstUc" runat="server" />' 

Add user control to page at run time.
// Load the control by calling LoadControl on the page class. Control c1 = LoadControl("test.ascx"); // Add the loaded control in the page controls collection. Page.Controls.Add(c1);

Custom control
Custom controls are compiled code components that execute on the server, expose the object model, and render markup text, such as HTML or XML, as a normal Web Form or user control does. In new project window select in web select ASP.net server control and then write code in control's class. Now you can override render method of control to display as you want on rendering of control.
namespace FirstCustomControl {
 [DefaultProperty("Text")]
    [ToolboxData("<{0}:CustomEmailLink runat=server></{0}:CustomEmailLink>")]
    public class CustomEmailLink : WebControl {
        [Bindable(true)]
        [Category("Appearance")]
        
        [Localizable(true)]
        public string DisplayName {
            get {
                String s = (String)ViewState["DisplayName"];
                return ((s == null) ? "[DisplayName]" : s);
            }

            set {
                ViewState["DisplayName"] = value;
            }
        }
        [Bindable(true)]
        [Category("Appearance")]
        [Localizable(true)]
        public string Email {
            get {
                String s = (String)ViewState["Email"];
                return ((s == null) ? "[Email]" : s);
            }

            set {
                ViewState["Email"] = value;
            }
        }
        [Bindable(true)]
        [Category("Appearance")]
        [Localizable(true)]
        public string Subject {
            get {
                String s = (String)ViewState["Subject"];
                return ((s == null) ? string.Empty : s);
            }

            set {
                ViewState["Subject"] = value;
            }
        }
        [Bindable(true)]
        [Category("Appearance")]
        [Localizable(true)]
        public string Body {
            get {
                String s = (String)ViewState["Body"];
                return ((s == null) ?string.Empty : s);
            }

            set {
                ViewState["Body"] = value;
            }
        }
        protected override void RenderContents(HtmlTextWriter output) {
            if (this.DesignMode) { RenderDesign(output); } else {
                if (this.Visible) {
                    RenderRuntime(output);
                }
                else {
                    return;
                }
            }
        }

        private void RenderRuntime(HtmlTextWriter output) {
            HyperLink link = new HyperLink();
            link.ID = this.ID;
            link.Text = this.DisplayName;
            link.NavigateUrl=string.Format("mailto:{0}",this.Email);
            if (!string.IsNullOrEmpty(Subject)) {
                link.NavigateUrl = link.NavigateUrl + "?subject=" + this.Subject;
                link.NavigateUrl = link.NavigateUrl + "&body=" + this.Body;
            }
            link.RenderControl(output);
        }

        private void RenderDesign(HtmlTextWriter output) {
            output.Write("Display Name:{0}<br/>Email:{1}<br/>Subject:{2}<br/>Body:{3}", this.DisplayName, this.Email,this.Subject,this.Body);
        }
}        
    }


You can add control to tool box
Right click on tool box select 'choose items', then select .net components, then browse custom control's dll. Now you can use this custom control on pages like other controls.

User control Vs Custom Control 
1. You can use custom control in your application by adding assembly reference to application while you need separate copy of user control in each application. 
2. You can add custom control in tool box while user control can’t be added. 
3. Custom control can be used in multiple applications by adding assembly to the GAC for same machine. 
4. Custom controls are difficult to create but easy to use in multiple applications. 
5. User controls are easy to create but difficult to use in multiple application.

Friday, October 29, 2010

Threading

Threading enables concurrent processing, you can perform multiple tasks simultaneously.

Multithreading is the ability of operating system to concurrently run programs or tasks in separate threads.
Multithreading requires OS those can perform it, and we written programs in such manner that uses this ability of OS.
It’s a fast computation because it runs multiple tasks simultaneously in different threads.
Basically it’s a game of operating system, tasks not run simultaneously os allots time slots to each thread and runs threads for those allotted time slots, user response is very slow compare to system so user feels like processes running concurrently.
How threading works
Application domains run in processes, and each application domain starts with a single thread and then a thread can call other threads. Operating system divided processor time among threads, it allotted time slots to threads to be executed slots depends on priority, os and thread size.
When a thread switches from running state to suspended os saves context (information) for it, and loaded context of thread to be executed.
Thread pool class – To manage group of threads.
Timer - Enable calling to delegates after a certain amount of time.
Mutex - Mutex class is used to protect simultaneous access of a shared resource. State of Mutex object is set to 'signaled' when it is not owned by any thread or 'nonsignaled' when owned by any thread, so treads can own it one by one.

Pausing and resuming threads
Method Thread.Sleep(miliseconds) immediately suspend a thread for given milliseconds and other thread uses this time slice.
Thread.Sleep(Timeout.Infinite) - Sends to sleep for infinite time.
Thread.Abort() - Aborted the thread.
Thread.Interrupt() - Interrupt the thread.

Overview
1. Threads enables concurrent processing.
2. System.Threading provides classes and interfaces for it, ex to create, start, abort, suspend, synchronization of multiple threads etc.
3. Threads share application resources.

Using System.Threading;

Thread thrd = new Thread(new ThreadStart(obj.Method));
thrd.start();


Friday, October 22, 2010

Asynchronous Calling to a method

We can call a method asynchronously by using beginInvoke and endInvoke methods of delegate,
we pass method's parameters to beginInvoke method then we have got to pass return value of beginInvoke method to endInvoke method, endInvoke method returns actual result(return type of method).
Asynchronous call to a method runs method in a separate thread.
Once you ask the framework to call something asynchronously, it needs a thread to do the work. It can not be the current thread, because that would make the invocation synchronous (blocking). Instead, the runtime queues a request to execute the function on a thread from the .NET Thread Pool. You don’t really need to code anything for it, all of it happens in the background. But, just because it is all transparent doesn’t mean you should care about it. There are a few things to remember:
  • FlushToDisk is executed on a separate thread, a thread that belongs to the .NET Thread Pool.
  • A .NET Thread Pool normally has 25 threads in it (you can change that limit), and each time  FlushToDisk is called, it is going to be executed on one of these threads. You can't control which one.
  • The Thread Pool has its limits! Once all the threads are used, an async method invocation is queued until one of the threads from the pool is freed. This is called Thread Pool Starvation, and normally when it comes to that, performance is compromised.

class DataCache {
public int FlushToDisk(string fileName) {
// simulate a long operation
Thread.Sleep(4000);
return 0;
}
}

class Program {
// define a delegate for the long operation
delegate int CacheFlusher(string fileName);
static void Main(string[] args) {
// create the object and then the delegate
DataCache cache = new DataCache();
CacheFlusher flusher = new CacheFlusher(cache.FlushToDisk);
// invoke the method asynchronously
IAsyncResult result = flusher.BeginInvoke("data.dat", null, null);
// get the result of that asynchronous operation
int retValue = flusher.EndInvoke(result);
Console.WriteLine(retValue);
}
}


Method # 01
// begin execution asynchronously
IAsyncResult result = flusher.BeginInvoke("data.dat", null, null);
// wait for it to complete
while (result.IsCompleted == false) {
// do some work
Thread.Sleep(10);
}
// get the return value
int returnValue = flusher.EndInvoke(result);


Method # 02
// call the delegate asynchronously
IAsyncResult result =
flusher.BeginInvoke("data.dat", null, null);
// wait for the call to finish
result.AsyncWaitHandle.WaitOne();
// get the return value
int returnValue = flusher.EndInvoke(result);


Method # 03
static void Main(string[] args) {
// create the object
DataCache cache = new DataCache();
// create the delegate
CacheFlusher flusher = new CacheFlusher(cache.FlushToDisk);
// call the delegate asynchronously
flusher.BeginInvoke("data.dat", new AsyncCallback(CallbackMethod), flusher);
// wait to exit
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
static void CallbackMethod(IAsyncResult result) {
// get the delegate that was used to call that
// method
CacheFlusher flusher =
(CacheFlusher) result.AsyncState;
// get the return value from that method call
int returnValue = flusher.EndInvoke(result);
Console.WriteLine("The result was " + returnValue);
}

Thursday, October 14, 2010

Sql - Function Vs Stored Procedure

Functions

1. Can be used with Select statement.
2. Not returns output parameter but returns table variables.
3. You can join UDFs.
4. Can not be used to change server configuration.
5. Can not be used with XML FOR clause.
6. Can not have transaction within function.


Stored Procedures

1. Used with EXEC or EXECUTE.
2. Returns output parameter.
3. You can not join SPs.
4. Can be used to change server configuration.
5. Can be used with XML FOR Clause.
6. Can have transaction within SP.

Sunday, October 10, 2010

Using Scenario - Abstract Class Vs Interface

Abstract class

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated.

The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

Interface

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the declaration of methods.

As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.


Using Scenario - Abstract Class Vs Interface

1. If you want to create multiple versions of your component, means need to create some new version in future then use abstract class because you can update abstract class and all classes derived from it updated automatically. While If you need to update interface it's not allowed, you will have to create whole new interface.

2.
If your base functionality will be useful for a wide disparate or unrelated range of classes then create interface, because abstract classes should be created for something closely related classes.

3.
If you have requirement of common, implemented base functionality then create abstract class because abstract class allow implementation also of members while in interface you can not implement any member.
If you need to have some code, data, access modifiers in functionality then use abstract class, in interface all members are public by default.

4.
If you are designing small base functionality then create interface for large base functionality use abstract class.

Thursday, September 30, 2010

Abstract and Sealed concepts

Abstract classes and members

Abstract keyword used to define class and class members for the purpose of inheritance.
An abstract class can't be instantiated and an abstract method doesn't have definition in base class, declaration followed by semicolon.

public abstract classA
{
public abstract void dowork(int i); //Abstract method has only declaration in base class
}

A non abstract derived class of an abstract base class must define all the abstract methods of base class and inherited abstract members from upper hierarchy of base class.
public classB : classA
{
public override void dowork(int i)
{
//Implementation of abstract method of base class
}
}

A. Should not define public or protected internal constructor.
B. Can be define Protected or internal constructor.
C. Abstract members are implicitly Virtual.
D. Declaring an abstract member as Virtual or Static is an error.
E. Abstract class may contain non abstract members, non abstract members can have definition in abstract class, meant common method for all derived classes without overriding the method.
F. An abstract derived class can define or not define abstract members of base class.
G. An abstract class can't be declared as Sealed, because having opposite meaning.
H. Non abstract class can't contain abstract members, abstract method can be declared in Abstract class.
I.  An abstract method declaration don't have braces {}, declaration followed by semicolon only.
    Ex.  public abstract void dowork(int i);
J. An Abstract class must implement all members of inherited Interface but not required to override all abstract members of inherited base class.
k. Abstract method declaration is allowed to override a virtual method of base class.

class A
{
   public virtual void F() {
      Console.WriteLine("A.F");
   }
}
abstract class B: A
{
   public abstract override void F();
}
class C: B
{
   public override void F() {
      Console.WriteLine("C.F");
   }
}

Purpose of abstract class to make common definition of a base class that multiple derived classes can share.
A class library has a abstract class than programmers can use the library and have their own implementation of derived class using base abstract class.

Ex.
     public abstract class Animals
    {
        public void Move()  //Non Abstract function
        {
            string s = "All animals can move";
        }
        public abstract void Breath();   
    }
    public class Dogs : Animals
    {
        public Dogs() { }
        public override void Breath()
        {  //Breath in open air
        }
    }
    public class Fish : Animals
    {
        public Fish() { }
        public override void Breath()
        {  //Breath in water
        }
    }
Dogs DaburMan = new Dogs();
            DaburMan.Breath();   //Abstract function of base abstract class
            DaburMan.Move();     //Non Abstract function of base abstract class
       Fish Shark = new Fish(); 
            Shark.Breath();  //Abstract function of base abstract class
            Shark.Move();    //Non Abstract function of base abstract class

***********************

Sealed classes and members


A sealed class can't be inherited, Sealed keyword is used to protect from derivation a class.
A sealed class can't be abstract, because of opposite meaning.
A sealed method also can't be override in derived class.
When applied to method or property sealed keyword always used with override keyword.

If you override an base class virtual method in derived class, you can declare that sealed there(on override) to protect override of that method in further derived classes. This negates the virtual aspect of the member for any further derived class.

public class D : C
{
public sealed override void DoWork()
{
// Implementation
}
}

Scenario - Creating Sealed class
1. To take away inheritance feature from users so they can't inherit that class.
2. If we have some internal operation/s in class or function, because access of class or function in this case can be harmful. ex. .net's string class is sealed.
3. If we have static members in class(Static members are sealed by default). ex pen, brush classes are sealed.

Saturday, September 25, 2010

What's new in the .NET framework version 3.5

  1. Framework - 3.5 extends many new features like Linq, WCF those are useful to develop pocket PC, smart phone and distributed mobile applications.
  2. ASP.Net -
    1. 3.5 includes AJAX while in 2.0 it needs to install. Microsoft AJAX library supports client-centric, object orient development which is browser independent. ScriptManager to make a page AJAX enable. UpdatePanel to target a specific area of page rather than refreshing whole page.   
    2. Visual web developer includes improved intellisense for java script and Ajax library.
    3. Listview control displays data provided by data source by using user defined templates. User can select, insert, update, delete and sort records. Listview includes features of data grid, grid view, data repeater and other similar list controls available in 2.0.
    4. Data pager provides paging functionality to data bound controls those implements ‘Ipageableitemcontainer’ interface like listview control.
    5. LinqDataSource for Linq(Language integrated query).
    6. ASP.Net Merge Tool to merge precompiled assemblies (aspnet_merge.exe) .
  1. Add-Ins and Extensibility - 3.5 introduces new architecture and model that enables powerful and flexible support to developers to develop extensible applications.

  2. CLR – 3.5 has improved CLR. Also has improvements in collection, garbage collection, better reader and writer locks in threading, i/o and pipes, reflection, diagnostics etc.

  3. Cryptography – 3.5 includes improved features for security. Some new cryptography classes added those used to verify and obtain information of manifest signature. 3.5 supports suite B cryptography algorithms published by National Security Agency(NSA).

  4. Networking Several features of networking get improved in 3.5. Peer to peer networking is server less networking technology allows network devices to share resources and communicate with each other directly, is get improved in 3.5.

  5. LINQ Its a new feature in 3.5 extends powerful query capabilities to language syntax of C#, VB.Net. Its standard, easy to understand and learn. 3.5 extends some assemblies those enable the use of Linq to query .net collections, databases, xml documents, ado.net data sets.
    System.Linq – (exist in System.core.dll) Extends standard operators and types for Linq.
    System.Data.Linq – Enables interaction with databases.
    System.Data.Linq.Mapping – Enables to generate Linq to Sql object model.
    System.xml.Linq – Enables Linq to access and modify xml documents.

  6. Expression trees – Expression trees are new in .net 3.5, it provides a way to present language level code in the form of data.

Thursday, September 2, 2010

SQL SERVER - Sql Server2000 Vs Sql Server 2005

  1. In 2005 enterprise manager and query analyzer given together, you can also open multiple windows in same enterprise manager.
  2. In 2005 you can create 2(pow(20)-1) databases while in 2000 its 65,535.
  3. 2005 introduced some new data types like ‘xml’.
  4. In 2005 you can store large value and object type by using ‘max’ like varchar(max), nvarchar(max), varbinary(max).
  5. In 2005 you can write try – catch statements in stored procedure.

    NSRI (shortcut to remember) in Sql Server 2005 –

    Notification services enhancement
    Service broker
    Reporting service enhancement
    Integration service enhancement

Delegate

A delegate is a type that defines a method signature. When you create an instance of the delegate, you can associate a method to the instance of compatible signature, now you can call or invoke that method by the delegate instance.
Delegates are used to pass a method as argument to other method. A delegate instance can be assigned a method of any accessible class or struct that matches signature of delegate, method can be static or instance method.
Ex.
Public Delegate int myDelegate(int x, int y); //Delegate declaration
Public int add(int a, int b) //Method definition
{
Return a+b;
}
myDelegate del = add;  //Delegate instance del assigned method ‘add’
                                   //(Equivalent to  myDelegate del = new myDelegate(add); )

del(12, 30); //call or invoke

General terms
1. Delegates are like function pointers in C or C++.
2. Delegates can be used to pass a method as argument to other method.
3. Delegates can be chained together, multiple methods can be called on a single event. When you call a delegate that is chained(added multiple delegates) then all the methods called on this single call this is called Multicasting or Chaining of delegates. All methods called in the sequence in which they added. 
4. Covariance allows a more derived return type method to be assign than delegate’s return type.
5. Contravariance allows less derived parameters type method to be assign than delegate’s parameter’s type.
6. Framework 2.0 introduced anonymous methods, which allows code blocks to be passed to delegate as parameter in place of separately defined method.
Code block may contain anonymous method or lambda expression. 

//Instantition of myDelegate with instance mdel assigned anonymous method
myDelegate mdel = delegate(int m, int n) {
//Code block
}
//Instantition of myDelegate with lambda expression
(input parameters) => expression //lambda expression


myDelegate mdel =  (int x, int y) => { Code block }
OR
myDelegate mdel =  (x, y) => { Code block }  //Compiler infer input types by own

mdel(20,100); //Call or invoke
7. Delegates types ex. del (instance of delegate - myDelegate del; ) are drived from Delegate class, delegate types are sealed they can not be derived from.
8. When you invoke delegate, parameters passed to the delegate, pass to the method and returns value (if have return type) through delegate, its not possible to create custom class from Delegate class.
9. Instance of delegate is an object so it can be assign to a property or can be pass to a method as parameter and call the delegate at some later time this is called
Asynchronous callback.
10. Delegate can be assign static method.
11. A delegate can be chained (multicast) with static and instance both type methods together.


In C# 1.0 and later, delegates can be declared as shown in the following example.
// Declare a delegate.
delegate void Del(string str);

// Declare a method with the same signature as the delegate.
static void Notify(string name)
{
    Console.WriteLine("Notification received for: {0}", name);
}
// Create an instance of the delegate.
Del del1 = new Del(Notify);

C# 2.0 provides a simpler way to write the previous declaration, as shown in the following example.
// C# 2.0 provides a simpler way to declare an instance of Del.
Del del2 = Notify;

In C# 2.0 and later, it is also possible to use an anonymous method to declare and initialize a delegate, as shown in the following example.
// Instantiate Del by using an anonymous method.
Del del3 = delegate(string name)
    { Console.WriteLine("Notification received for: {0}", name); };

In C# 3.0 and later, delegates can also be declared and instantiated by using a lambda expression, as shown in the following example.
// Instantiate Del by using a lambda expression.
Del del4 = name =>  { Console.WriteLine("Notification received for: {0}", name); };

Combining or multicasting of delegates
Public Delegate void Del(String s);
Class Test
{
Static void hello(string s)
{
System.Console.WriteLine(“Hello {0}!”,s);
}

Static void Goodbye(string s)
{
System.Console.WriteLine(“Good Bye {0}!”,s);
}

Static void main()
{
Del a, b, c, d;
a = hello; //Assigning hello method to delegate a

b = Goodbye; //Assigning hello method to delegate a

c = a + b; // ( OR c = a; c += b;)

d = c – b; // ( OR d = c; d -= b;)
a(“Ram”); // Invoke delegate a
b(“Shyam”); // Invoke delegate b
c(“Ravi”); // Invoke delegates a then b
d(“Shubham”); // Invoke delegate a
}
}
Output
Hello Ram! //result of a
Good Bye Shyam! //result of b
Hello Ravi!     //result of c
Good Bye Ravi!
Hello Shubham! //result of d

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 ",".

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...