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
Why not just use the else ?
if (child is IContainer)
{
//
}
else
{
// Do what you want here
}
Its neat it familiar and simple ?
The extension method IsNot<T>
is a nice way to extend the syntax. Keep in mind
var container = child as IContainer;
if(container != null)
{
// do something w/ contianer
}
performs better than doing something like
if(child is IContainer)
{
var container = child as IContainer;
// do something w/ container
}
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.
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."
public static bool Is<T>(this object myObject)
{
return (myObject is T);
}
public static bool IsNot<T>(this object myObject)
{
return !(myObject is T);
}
Then you could write:
if (child.IsNot<IContainer>())
{
// child is not an IContainer
}
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) { ... }
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>()) { // ...
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");
}