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...
Solution 1:
if(!(child is IContainer))
is the only operator to go (there's no IsNot
operator).
You can build an extension method that does it:
public static bool IsA<T>(this object obj) {
return obj is T;
}
and then use it to:
if (!child.IsA<IContainer>())
And you could follow on your theme:
public static bool IsNotAFreaking<T>(this object obj) {
return !(obj is T);
}
if (child.IsNotAFreaking<IContainer>()) { // ...
Update (considering the OP's code snippet):
Since you're actually casting the value afterward, you could just use as
instead:
public void Update(DocumentPart part) {
part.Update();
IContainer containerPart = part as IContainer;
if(containerPart == null) return;
foreach(DocumentPart child in containerPart.Children) { // omit the cast.
//...etc...
Solution 2:
You can do it this way:
object a = new StreamWriter("c:\\temp\\test.txt");
if (a is TextReader == false)
{
Console.WriteLine("failed");
}
Solution 3:
New In C# 9.0
https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#logical-patterns
if (part is not IContainer)
{
return;
}
Original Answer
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;
}
Solution 4:
C# 9 (released with .NET 5) includes the logical patterns and
, or
and not
, which allows us to write this more elegantly:
if (child is not IContainer) { ... }
Likewise, this pattern can be used to check for null:
if (child is not null) { ... }