C# : ‘is’ keyword and checking for Not

This is a silly question, but you can use this code to check if something is a particular type…

if (child is IContainer) { //....

Is there a more elegant way to check for the “NOT” instance?

if (!(child is IContainer)) { //A little ugly... silly, yes I know...

//these don't work :)
if (child !is IContainer) {
if (child isnt IContainer) { 
if (child aint IContainer) { 
if (child isnotafreaking IContainer) { 

Yes, yes… silly question….

Because there is some question on what the code looks like, it’s just a simple return at the start of a method.

public void Update(DocumentPart part) {
    part.Update();
    if (!(DocumentPart is IContainer)) { return; }
    foreach(DocumentPart child in ((IContainer)part).Children) {
       //...etc...

13 Answers
13

Leave a Comment