This is a silly question, but you can use this code to check if something is a particular type...
if (child is IContainer) { //....
Is ther
This hasn't been mentioned yet. It works and I think it looks better than using !(child is IContainer)
if (part is IContainer is false)
{
return;
}
https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#logical-patterns
if (part is not IContainer)
{
return;
}
Ugly? I disagree. The only other way (I personally think this is "uglier"):
var obj = child as IContainer;
if(obj == null)
{
//child "aint" IContainer
}
if (child is IContainer ? false : true)
The is
operator evaluates to a boolean result, so you can do anything you would otherwise be able to do on a bool. To negate it use the !
operator. Why would you want to have a different operator just for this?
While the IS operator is normally the best way, there is an alternative that you can use in some cirumstances. You can use the as operator and test for null.
MyClass mc = foo as MyClass;
if ( mc == null ) { }
else {}
While this doesn't avoid the problem of parentheses, for the sake of people getting here via Google, it should be mentioned that newer syntax exists (as of C# 7) to make the rest of your code a little cleaner:
if (!(DocumentPart is IContainer container)) { return; }
foreach(DocumentPart child in container.Children) {
...
This avoids the double-cast, the null-check, and having a variable available in scopes where it could be null.