Using is and as keyword in C# instead of reflection

Hi

Now a days people are so much relayed on the casting reference types and reflection that they forget the use of the other keyword in the system to work out the same. I support the use of the inbuilt keywords like as and is because they are faster and many a times they also make us rely on hard coding the type of the object.

Reflection is a very powerful tool but it also has some performance degradation as against the inbuilt keywords. Also if we use the inbuilt keywords we don’t have to hard code the type in the code. With reflection to check the type of an object we would write the following code.

if(Variable.GetType() == Type.GetType("System.String"))

Here we are using reflection to get the type of the variable. It has 2 disadvantages. First of all it’s using which has its own performance hit and second that for checking purpose the type of the Variable has been hard coded. We can do the same task simply without using any reflection.

if(Variable is string)

In the above code we are not using any reflection, but still are able to compare the type of the Variable very easily and the code would be extremely fast.

Also while casting a variable to one type we use reflection even when we can do away with it.

myVariable = (string)Request["myVariable"];

can easily be written as

myVariable = Request["myVariable"] as string;

Here if the variable cannot be cast the IL will return a null value. This method would only work for reference type. For value types like int etc we can use System.convert.

Hope this helps
Thanks
Vikram


Share this post   Email it

Feedback

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Copyright © 2006 - 2010 Vikram Lakhotia