Monday, July 25, 2011

C#

Abstract Class Vs Interfaces
There have a bit confusion between abstract classes and interfaces.I also had lot of issues about these two concepts.I'm going to explain about that why both abstract classes and interfaces required.

Think Animal is one of the abstract class.So it can have implemented methods(concrete methods) and non implemented methods(abstract methods).
ex:

abstract class Animal
    {
        abstract void eating;
        abstract void talking;
        abstract void breathing;
        public void watching
        {use eyes to see; }



    }

If any class going to implement that abstract class it has to implement this all abstract methods in their own way

But every animal must implement these abstract methods as their requirement.they can't omit any of them.
class fish : Animal
    {
        override void eating
        {eat seafoods; }
        override void talking
        {usually keep silent; }
        override void breathing
        {breath using fins; }
    }

    class Cat : Animal
    {
        override void eating
        {eat rice and fish; }
        override void talking
        {myaaw.... sound; }
        override void breathing
        {breath using nose; }
    }

Think IFly and ISwim as interfaces.These interfaces can specify functionalities for fly and swim.So if an animal can swim or fly they need to implement these interfaces.
So interface is like a contract.If we going to implement an interface we faithfully promises to implement the methods and members of it.
But abstract class act as a base.It can have implemented methods and abstract methods too.These  implemented methods are common to all derived classes and abstract methods need to implement by derived class as their requirement


Generic Classes
Generics is a new feature in C# 2.0.C# classes alow programmers to create classes support for any type.When we instatiate we can specify a specific type for each instanse.
let's look at an example

this code will result as below,


Class MainProgram
{
        static void Main(string[] args)
        {
            GenericClass<int> obj1 = new GenericClass<int>();
            Console.WriteLine("int object passing...\n");
            obj1.MyGenericMethod<int>(12, 213);
            GenericClass<string> obj2 = new GenericClass<string>();
            Console.WriteLine("string object passing...\n");
            obj2.MyGenericMethod<string>("Hello", 222);
            GenericClass<float> obj3 = new GenericClass<float>();
            Console.WriteLine("float object passing...\n");
            obj3.MyGenericMethod<float>(232.32F, 222);

            Console.Read();
        }

    }

    class GenericClass<T>

    {

        List<T> al = new List<T>();
        public void MyGenericMethod<T>(T var1, int var2)
        {
            Console.WriteLine("Variable1=" + var1.GetType() + "\nVaiable2=" + var2);
        }

    }

int object passing....
Variable1=System.Int32
Variable2=213

string object passing....
Variable1=System.String
Variable2=222

Float object passing....
Variable1=System.Single
Variable2=222

as that above result generic class can create instant for specific type.so programmers can reuse that code for variouse data types.


New KeyWord

"new" Keywod has several usages in the C# language. In this blog I suppose to explain these usages separately.
Most cases we used new key word to create new instances .for example,this

MyClass object1 = new MyClass();

New keywod use to initialize variables with default values
Ex.  int MyintNumber = new int();
This is totally same to  int MyintNumber =0;
Use the new keyword to explicitely hide a member from the base class.
Ex.
Base class Member :
public void MyMethod(int var1)
        {
            Console.WriteLine("This is Base Class Member");
        }

Derived Class Member
  public void MyMethod(int var1)
        {

            Console.WriteLine("This is Derived Class Member");

        }

In above case derived class member hide the base class member.when you going to compile the derived class you will get a warning.
Warning:
MyDerivedClass.MyMethod(int)' hides inherited member MyBaseClass.MyMethod(int)'. Use the new keyword if hiding was intended.            
To avoid that warning you can use new keyword with derived class member as a modifier and it allow to explicitly hiding base members. Hiding concept is totally different from overriding concept.

Casting in C#

Simply casting means convert one data type into another. But there have some constraints to cast one type to another. In C# there have 2 casting types
  1. Implicit Casting
  2. Explicit Casting

If the conversion is implicit, then you don't have to specify the cast. You only need to assign one data type to another. Before use implicit casting you have to think about following things,
  • Is there having a risk to information loss. Usually use with integral data type. It means size of the conversion data type must large or equal to the size of previous data type. As an example if you going to convert long to int you'll get an exception.
  • Is that conversion throwing any exceptions from overload? As an example, think you try to convert int to string. The operation will fire an exception because you can't overload string into the int method.
Ex:
long l = 10;
int i = l;//Compilation error
(Size of int is less than the size of long. So you can’t put long type variable inside the long.)

double d = 12.5;//Compilation error(Can't overload int into double)
int i = d;If the conversion can fire any exception or have a risk of information loss you have to use the explicit casting.

Basic Syntax for Explicit Casting
datatypeA variableA = value;
datatypeB variableB = (datatypeB)variableA;

datatypeA is type of source data
datatypeB is type of destination data

Ex:
long var1 = 12;
int var2 = (int)var1;

double d = 12.21;
int i = (double)d;

But there have issues to casting between non-compatible data types such as strings and numeric types. For overcome that issue .Net framework provides a helper class called ‘Convert’. And also you can use parsing method for that case.

Ex:

int i = Convert.ToInt32(s);
string s = "10";
 //Value of i=10;



as casting

We can use as operator to casting for perform in more efficient and less errors. 
If we use as operator to casting it will avoid firing exception when fail to cast. Instead of that it will return null.
As operator can only use casting between reference types or nullable types. as casting is only support for Downcasting operation. DownCasting is casting from Top to Bottom of Class hierarchy.

Ex:

BaseClass b=d as BaseClass ();
DerivedClass d=new DerivedClass ();
 //Success.(Support for DownCasting)



DerivedClass d=b as DerivedClass();
BaseClass b=new BaseClass();
//Passing null.(Not Support for UpCasting)


 editing................
DownCasting is Casting from Top to Bottom of Class hierarchy.

 editing................


Casting is unavailable when converting between strings and numeric values. Instead, the .NET framework provides a 'Convert' class specifically designed for converting between native types. The numeric types also provide methods for parsing strings.
dynamic casting
as casting

Boxing and unBoxing
Boxing=implecit value to ref
unboxing= explict ref to vale


is Operator
If you need to know exactly the variable we want to cast is really from the same type that we need to use, we can apply “is’ operator. This “is” operator is usually used to prevent unnecessary casting.
For that case we can use “is” operator.

Object obj ="hello";
String s=String.Empty;
S=((obj is string)string)obj; //Casting Success

Object obj = 1;
String s=String.Empty;
S=((obj is string)string)obj; //Casting fail
Reference Type Vs Value Type
 There have mainly 2 data types in C#.
  • Value Type
  • Reference Type
value type variables store actual data in it self and they store in a memory as a stack. But reference type variables store memory address of actual data in it self and those address can point to actual data. These actual data refetrenced by reference type variable store in a memory as a heap but variables itself store in the memory as a stack like value types.

Reference Type:- Class,Interface,Delegate,Object,String
Value Type:-All the numeric types,Structs,Enumerations 

Note

·         Value types cannot be inherited
·         For the all type of variables we can assign there default values by initialize them using 'new' key word
·         If you use 'new' keyword to initialize struct it will assign default value to all its instant members
Ex:-
class MyProgram
    {
        static void Main(string[] args)
        {

            Point myPoint = new Point();
            Console.WriteLine("xVal:-"+myPoint.xVal+"\nyVal:-"+myPoint.yVal+"\ndecimalPoint:-"+myPoint.decimalPoint+"\nisSet:-"+myPoint.isSet+"\ncharVal:-"+myPoint.charVal);
            Console.ReadLine();

        }
    }

    struct Point
    {
        public int xVal;
        public long yVal;
        public decimal decimalPoint;
        public bool isSet;
        public char charVal;

    }

Output
xVal:-0
yVal:-0
decimalPoint:-0
isSet:-False
charVal:-

Boxing and Un-Boxing
Boxing
Assign value type variable to a reference type variable. This mean we are going to move data of the variable from stack to heap.

Un-Boxing
Assign reference type variable to a value type variable. This mean we are going to move the data of the variable from heap to stack. But variable itself stay where it was.
 

No comments:

Post a Comment