C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » C# Syntax »

Best practice to handle the type casting


Posted Date: 05 Oct 2009    Resource Type: Code Snippets    Category: C# Syntax
Author: vinayaka krishna ShenoyMember Level: Silver    
Rating: 1 out of 5Points: 5



Hi,

One of the best ways/practices to handle the type casting which we come across quite often in Object oriented programming in c# is by using the 'as' operator as shown below.


public class BaseClass
{
public int i;
}

public class DerivedClass : BaseClass
{
public int j;
}

How to call...

BaseClass b = new BaseClass();
DerivedClass d = new DerivedClass();

b = d as BaseClass;
if (b != null)
{
//Handle the further logic
}


Advantage of using as over the other technique(by using (type)), if the cast is not valid, then the exception wont be raised, instead of that null is returned.(Exception is the costliest operation)

I hope this helps.

Regards,
-Vinayak



Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Best Practices  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Prevent Closing Window Forms In C#.Net
Previous Resource: Simple Steps to use of Delegate
Return to Discussion Resource Index
Post New Resource
Category: C# Syntax


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use