Will using the "as" keyword when using type conversion not through an Invalid cast exception If so how would i make this statement the same but use the as keyword instead of the =
_EndingVendorLegs.EndID = ((Tracking.BusinessObjects.
StopOrderLegDetail)tempOrderManifest[this.tempOrderManifest.Count - 1]).StopID;I want to see if it could be
_EndingVendorLegs.EndID as ((Tracking.BusinessObjects.StopOrderLegDetail)tempOrderManifest[this.tempOrderManifest.Count - 1]).StopID;
but i get "type expected" I am not sure how i need to code the line,,,, any help

Using the "as" Keyword
IrishAnto
The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int ' is the warning i get when doing the above code segment....
if(_EndingVendorLegs.EndID == null){
_EndingVendorLegs.EndID = ((Tracking.BusinessObjects.
StopOrderLegDetail)tempOrderManifest[this.tempOrderManifest.Count - 2]).StopID;}
curiousss
it should be:
_EndingVendorLegs.EndID = _EndingVendorLegs.EndID as ((Tracking.BusinessObjects.StopOrderLegDetail)tempOrderManifest[this.tempOrderManifest.Count - 1]).StopID;
but this still may not work. you are needing to use a Type (object/class) to try to make the object into that type, should it support it. Example:
this.theTextBox = this.theTextBox as MyClass;
it will also not throw an exception but return null if it could not make the object into the specified type
k_Prasad
hi,
Divide the statement into two like:
Assuming Tracking.BusinessObjects.StopOrderLegDetail is typeX, that
TypeX Instance = tempOrderManifest[this.tempOrderManifest.Count - 1] as typeX;
_EndingVendorLegs.EndID = instance.StopID;
Hope it helps
Dietz
as operator is great feature but should be used basically for reference types. There are some situations when should not be used like:
- you can't use as operator when casting value to value type.
- you are not performing unboxing conversion
First case is a reason why you can't use as operator to determine does EndID will receive value or will be null, because EndID is int type. That is why you always get false.
The code will be something like:
Tracking.BusinessObjects.StopOrderLegDetail detail = tempOrderManifest[this.tempOrderManifest.Count - 2] as Tracking.BusinessObjects.StopOrderLegDetail;
if (detail != null)
{
_EndingVendorLegs.EndID = detail.StopID;
}
Shaun Logan
Here:
_EndingVendorLegs.EndID = (tempOrderManifest[this.tempOrderManifest.Count - 1]).StopID as Tracking.BusinessObjects.StopOrderLegDetail;
if(_EndingVendorLegs.EndID == null) // Means Casting was invalid
{
//////
}
else
{
// Do you work here......
}
I hope this will help.
Best Regards,
Rizwan