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
|
No responses found. Be the first to respond and make money from revenue sharing program.
|