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...
Ugly? I disagree. The only other way (I personally think this is "uglier"):
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?The way you have it is fine but you could create a set of extension methods to make "a more elegant way to check for the 'NOT' instance."
Then you could write:
You can do it this way:
The extension method
IsNot<T>
is a nice way to extend the syntax. Keep in mindperforms better than doing something like
In your case, it doesn't matter as you are returning from the method. In other words, be careful to not do both the check for type and then the type conversion immediately after.