Showing posts with label CSharp. Show all posts
Showing posts with label CSharp. Show all posts

Saturday, 31 August 2013

What is the difference between Finalize() and Dispose()

C# Provides two special methods that are used to release the instance of a class from memory, Finalize() and Dispose().
Finalize(): The Finalize destructor is a special method that is called from the class to which it belongs or from the derived class. The Finalize() destructor is called after the last reference to an object is released from the memory. The .Net Framework automatically runs the Finalize() destructor to destroy objects in the memory. However, it is important to remember that the Finalize() destructor may not execute immediately when an object loses scope. It is called by CLR using reference-tracing garbage collection, the CLR periodically check for objects that are not used by the application. When such an object is found, the Finalize() destructor is called automatically and the garbage collector of the CLR release the object from the memory.

Dispose(): The Dispose() method is called to release a resource, such as database connection, as soon as the object using such a resource is no longer in use. Unlike the Finalize() destructor, the Dispose() method is not called automatically and you must explicitly call it from a client application when an object is no longer needed. The IDisposable interface contains the Dispose() method. Therefore , to call the Dispose() method, the class must implement the IDisposable interface.

Friday, 30 August 2013

Difference between Dynamic polymorphism and static polymorphism

In static polymorphism response to a function is decided at compile time. In Dynamic polymorphism response to a function is decided at run time. 1)Static polymorphism is achieved by method overloading where as run time polymorphism( or dynamic polymorphism) is achieved by method overriding. 2)static polymorphism uses the concept of compile time binding(or early binding) where as dynamic polymorphism uses the concept of runtime binding (or late binding). 3)Dynamic polymorphism is faster than static polymorphism. 4)To implement static polymorphism inheritance is not necessary where as to implement dynamic polymorphism inheritance is necessary. 5)Generally when a programmer want to extend existing feature in a software,method overloading(load + extra load(more lines of code)) is used,and a programmer uses method overriding when he wants to provide a different implementation.


Understanding Static & Dynamic Polymorphism with Examples.

What is polymorphism? Poly means many. So how can we take this definition in .NET context. Well we can apply this to class’s ability to share the same methods (actions) but implement them differently.
Suppose we have a method in a class to add numbers,
public class calculation
{
public int add(int x, int y)
{
return x+y;
}
}

So to perform addition of three numbers, we need similar add method but with different parameter
public class calculation
{
public int add(int x, int y)
{
return x+y;
}
public int add(int x, int y,int z)
{
return x+y+z;
}
}

So we can that class is sharing the same methods (actions) but implement them differently.
Now this is an example when we are sharing method name and implementing them differently, let’s take a scenario where implementation is in some derived class.
For instance, say we create a class called Shape and this class has a method called .Area () which calculates area. Then we create two subclasses, using inheritance, of this Shape class. One called Square, the other called Circle. Now obviously a square and circle are two entirely different shapes, yet both classes have the .Area() method. When the Square.Area() method is called it will calculate area of  a square. When the Circle.Area() method is called, it will calculate area of a circle. So both classes can use the same methods but implement them differently.
Now let’s dive little deeper and understand what we discussed above in more technical terms.
Types of Polymorphism
1) Static or Compile time Polymorphism
Which method is to be called is decided at compile-time only. Method Overloading is an example of this. Method overloading is a concept where we use the same method name many times in the same class, but different parameters. Depending on the parameters we pass, it is decided at compile-time only. The same method name with the same parameters is an error and it is a case of duplication of methods which c# does not permit. In Static Polymorphism decision is taken at compile time.
public Class StaticDemo
{
public void display(int x)
{
Console.WriteLine(“Area of a Square:”+x*x);
}
public void display(int x, int y)
{
Console.WriteLine(“Area of a Square:”+x*y);
}
public static void main(String args[])
{
StaticDemo spd=new StaticDemo();
Spd.display(5);
Spd.display(10,3);
}
}
2) Dynamic or Runtime Polymorphism.
Run time Polymorphism also known as method overriding. In this Mechanism by which a call to an overridden function is resolved at a Run-Time (not at Compile-time) if a base Class contains a method that is overridden. Method overriding means having two or more methods with the same name, same signature but with different implementation. In this process, an overridden method is called through the reference variable of a superclass, the determination of the method to be called is based on the object being referred to by reference variable.
Class BaseClass
{
Public void show ()
{
Console.WriteLine(“From base class show method”);
}
}
Public Class DynamicDemo : BaseClass
{
Public void show()
{
Console.WriteLine(“From Derived Class show method”);
}
Public static void main(String args[])
{
DynamicDemo dpd=new DynamicDemo ();
Dpd.show();

}
}
Here memory allocation will be at the run time for that particular method.

What is Virtual Function: They implement the concept of polymorphism are the same as in C#, except that you use the override keyword with the virtual function implementation in the child class. The parent class uses the same virtual keyword. Every class that overrides the virtual method will use the override keyword.
Why to use them:
1)    It is not compulsory to mark the derived/child class function with Override KeyWord while base/parent class contains a virtual method
2)    Virtual methods allow subclasses to provide their own implementation of that method using the override keyword
3)    Virtual methods can’t be declared as private.
4)    You are not required to declare a method as virtual. But, if you don’t, and you derive from the class, and your derived class has a method by the same name and signature, you’ll get a warning that you are hiding a parent’s method
5)    A virtual property or method has an implementation in the base class, and can be overriden in the derived classes.
6)    We will get a warning if we won’t use Virtual/New keyword.
7)    Instead of Virtual we can use New Keyword
class A
{
public void M()
{
Console.WriteLine(“A.M() being called”);
}

public virtual void N()
{
Console.WriteLine(“A.N() being called”);
}
}

class B : A


{


public new void M()


{


Console.WriteLine(“B.M() being called”);


}
public override void N()

{


Console.WriteLine(“B.N() being called”);


}


}
say
A a = new B();
a.M();


a.N();
The results would be
A.M() being called


B.N() being called



Override Keyword: method overriding is modifying or replacing the implementation of the parent class with a new one. Parent classes with virtual or abstract members allow derived classes to override them. class Shape
{
    public virtual void Draw()
    {
        Console.WriteLine(“Shape.Draw”)    ;
    }
}

class Rectangle : Shape
{
    public override void Draw()
    {
        Console.WriteLine(“Rectangle.Draw”);
    }
}

Friday, 19 July 2013

Nullable Types

Nullable types are instances of the Nullable struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.
class NullableExample
{
    static void Main()
    {
        int? num = null;

        // Is the HasValue property true? 
        if (num.HasValue)
        {
            System.Console.WriteLine("num = " + num.Value);
        }
        else
        {
            System.Console.WriteLine("num = Null");
        }

        // y is set to zero 
        int y = num.GetValueOrDefault();

        // num.Value throws an InvalidOperationException if num.HasValue is false 
        try
        {
            y = num.Value;
        }
        catch (System.InvalidOperationException e)
        {
            System.Console.WriteLine(e.Message);
        }
    }
}
The example will display the output:
num = Null
Nullable object must have a value.

Nullable types have the following characteristics:
  • Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)
  • The syntax T? is shorthand for Nullable, where T is a value type. The two forms are interchangeable.
  • Assign a value to a nullable type just as you would for an ordinary value type, for example int? x = 10; or double? d = 4.108. A nullable type can also be assigned the value null: int? x = null.
  • Use the Nullable.GetValueOrDefault method to return either the assigned value, or the default value for the underlying type if the value is null, for example int j = x.GetValueOrDefault();
  • Use the HasValue and Value read-only properties to test for null and retrieve the value, as shown in the following example: if(x.HasValue) j = x.Value;
    • The HasValue property returns true if the variable contains a value, or false if it is null.
    • The Value property returns a value if one is assigned. Otherwise, a InvalidOperationException is thrown.
    • The default value for HasValue is false. The Value property has no default value.
    • You can also use the == and != operators with a nullable type, as shown in the following example: if (x != null) y = x;
  • Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;
  • Nested nullable types are not allowed. The following line will not compile: Nullable<Nullable<int>> n;

C# LINQ Joins With SQL

There are  Different Types of SQL Joins  which are used to query data from more than one database tables. In this article, you will learn a...