We want to avoid having a NullReferenceException. Currently we have:
ISomeInterface interface = this.GetISomeInterfaceInstance();
(interface as ClassImplmentsISomeInterface).Method();
This works fine, but risks NullReferenceException. One solution would be:
ISomeInterface interface = this.GetISomeInterfaceInstance();
ClassImplmentsISomeInterface instance = interface as ClassImplmentsISomeInterface;
if (instance != null)
instance.Method();
But this produces a lot of extra code for a simple check (according to resharper there are 100s of possible NREs.) A second solution method is:
ISomeInterface interface = this.GetISomeInterfaceInstance();
if (interface is ClassImplmentsISomeInterface)
(interface as ClassImplmentsISomeInterface).Method();
But I gather that is actually uses as in the background, thus doing the cast twice, which I’d like to avoid. Does this matter? For example, is the C# compiler clever enough to optimise this performance issue away?
Is there some other technique I am missing here? Or is one of the above methods preferabled?
If you want to cast speculatively then your first option (
asandnullcheck) is recommended. However, you should also consider refactoring the code such that the cast is no longer required.