C# : 'is' keyword and checking for Not
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...
You can do it this way:
object a = new StreamWriter("c:\\temp\\test.txt");
if (a is TextReader == false)
{
Console.WriteLine("failed");
}
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;
}
New In C# 9.0
https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#logical-patterns
if (part is not IContainer)
{
return;
}