Hi Guys,
I am sort of new to C# language. Am I right to say that they are the same?
CurrencyManager cm=(CurrencyManager)this.BindingContext[DataSet1.Table[0]];
CurrencyManager cm=this.BindingContext[DataSet1.Table[0]] as CurrencyManager;
Am I right to assume that type casting can be done using either method? So far I have tried and both methods seem to have the same effect.
Is there anything which I am not aware of?
Maung Maung
The melody of logic will always play out the truth. ~ Narumi Ayumu, Spiral
A few differences between as and operator casting is as follows:
Well, all in all, that means try to use as instead because it doesn't attempt to create a new object while casting does, a little performance benefit over casting for that.
SO! When you do casting, you'll need to check for exceptions AND nulls.
You need not use is to check whether the conversion is successful, just do a null comparison. Usually we use is for development/testing purposes and gets commented/ignored when we go into production.
triplez wrote: You need not use is to check whether the conversion is successful, just do a null comparison. Usually we use is for development/testing purposes and gets commented/ignored when we go into production.
I don't quite get the use of is. Is that an operator or function in C#?
How can we use it? Any example?
is is basically to do a precheck of the casting before actually casting it. For example,
MyBaseType = _test; if(_myClass is MyBaseType) { _test = _myClass as MyBaseType;}
MyBaseType = _test;
if(_myClass is MyBaseType) { _test = _myClass as MyBaseType;}
It basically does a check for you to ensure that casting is possible. There is quite alot of performance hit to this, and doing it this way is prefered. You're basically casting it twice, hence the performance hit. Once to test it, the second to actually cast it. Usually we would do this for debugging purposes and comment it out or use a Conditional attribute to remove the method from compilation.
MyBaseType = _test; _test = _myClass as MyBaseType;if(_test == null) { // do your error thing, or you can do a != null and do your things} else { // you know the rest ya?}
_test = _myClass as MyBaseType;if(_test == null) { // do your error thing, or you can do a != null and do your things} else { // you know the rest ya?}
Basically as will ensure that SOMETHING will return, and if it isn't possible to cast it, it will return a null. Whereas for operator casting, it will either throw an exception, return a null, or convert. And you'll have to check for all cases.
Thanks for sharing.
Now I know what exactly these keywords mean in C#.
Triplez wrote: Well, all in all, that means try to use as instead because it doesn't attempt to create a new object while casting does, a little performance benefit over casting for that.
It is what he metioned in his previous post.