Roslyn: 'is' and 'as' operators can guarantee each other's result

Created on 7 Sep 2016  路  4Comments  路  Source: dotnet/roslyn

Can you confirm that if a statement that use is and returns true, substituting the 'is' operator with 'as' operator will result in not null result in all circumstances.

Example:

var result = instance is FooObject;
var result2 = instance as FooObject;

so if 'result' variable is 'true' it will guarantee that 'result2' will always be not null in all cases?

Most helpful comment

Yes, and that's why we're getting the new value is Type variableofType construct in C#7.

All 4 comments

Hi,

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

See also: https://msdn.microsoft.com/en-us/library/scekt9xw.aspx

if (instance is FooObject){
   var x = instance as FooObject
}

Will x guaranteed to be a valid casting and not return null in above case?

Yes, is and as use the same IL instruction, isinst.

EDIT: assuming instance isn't accessed by multiple threads. Otherwise it's theoretically possible for another thread to modify instance so it fails the 2nd time.

Yes, and that's why we're getting the new value is Type variableofType construct in C#7.

Was this page helpful?
0 / 5 - 0 ratings