Archive for April, 2013

How to use IS and AS keywords in C#

Using as keyword

Dynamic polymorphism which is evaluated at run time not at compile time so we are sure that errors are not known before execution. Like e.g Explicit casting is evaluated at run time.

object test = new Manager();
//You cant cast test to a Department!
Department dept= (Department) test;

So how can we safely use such casting and handle exception

try
{ 
Department dept = (Department) test;
}
catch(InvalidCastException ex)
{ 
...
}

Above code is about handling exception but how about doing some more logical coding in the failed case, coding into catch not good example.

We can determine whether the given type is compatible with another using ‘as’. Compatibility check will return null value.

Using is Keyword
Unlike as keyword is keyword returns false if compatibility between objects or casting failed.

void(Employee emp)
{
if(emp is Department)
     Console.WriteLine("Sorry, emp is not Department..");
}

Here we are checking runtime what incoming base class reference is actually pointing in memory. So we are not using try catch as well here to wrap the casting.

Happy programming..

Number of View :1277

No Comments


Interface Programming tool A Concept

Interface is technique or concept which is used to add set of behavior or functionality to be mandatory. When we derive into class then class has to implement each thing that is in Interface. Something like making skeleton and then giving different look and behavior using that skeleton. Decoupling of object and  its implementation is possible because of interface.

Lets say you create interface of Cycle

Interface ICycle
{
void Handle(); 
void Wheels(); 
}

Inheriting class

class AtlasCycle: ICycle
{
void ResizableHandle()
{...
}
void fourDiaWheels()
{....
}
}

 

Above cycle skeleton can be used to derive any brand of bicycle with different feature values.

  • Interface has by default all fields, properties and methods Public. But you can have internally private and use it appropriately inside interface.
  • One which is public has to be implemented in inheriting class So it better than having base class.
  • Class can inherit as many as interfaces So structures can also use interfaces.
  • Interface does not have implementation only declarations.
  • It is highly used to design architecture. So it is architecture job to define what to be exposed and what not to client.

Happy Programming..

Number of View :1266

No Comments



SetPageWidth
Content Protected Using Blog Protector By: PcDrome.

Mahol Dot Org is Stephen Fry proof thanks to caching by WP Super Cache