We had a discussion today on the job where we were talking about use case where you have code similar to this:
using System;
namespace test
{
class Program
{
public class A
{
public void Foo()
{
Console.WriteLine("This is A.");
}
}
public class B
{
public void Foo()
{
Console.WriteLine("This is B");
}
}
public static void Test(object obj)
{
if (obj is A a)
{
a.Foo();
}
else if (obj is B b)
{
b.Foo();
}
}
static void Main(string[] args)
{
Test(new A());
}
}
}
Then we discussed how the "is" keyword can be removed by abstracting the behavior like this (or with an interface, depending on which works best in the context):
using System;
namespace test
{
class Program
{
public abstract class Base
{
public abstract void Foo();
}
public class A : Base
{
public override void Foo()
{
Console.WriteLine("This is A.");
}
}
public class B : Base
{
public override void Foo()
{
Console.WriteLine("This is B");
}
}
public static void Test(Base obj)
{
obj.Foo();
}
static void Main(string[] args)
{
Test(new A());
}
}
}
So, from there, we were a bunch of people trying to figure out which would be the scenarios where the use of the "is" keyword would really be justified. All the examples we could come up with were ruled out as they resulted from other code smells..
I did some research on the web for an answer but most websites would only provide definitions and how to use the keyword but I couldn't find any source that I could cite for "good practices" related to the keyword.
In summary, my question is, what are (if any) scenarios where the use of the "is" keyword is justified (necessary/more elegant)?
Edit: More information to clarify. For a lot, if not most keywords/statements/directives, there are context where it makes sense to use it and other contexts where the use is unjustified.
For example, try
, catch
, throw
are great when you need to have a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. However, most programmers would agree that using them for control flow is a bad idea.
In that same regards, goto
can be used in switches or in nested loops and this is generally accepted usage. However, if you start using goto
to jump around in the code, this is, again, considered to be a bad idea by most programmers.
Therefore, I want to identify what use cases for is
would be accepted and what others would be rejected by most programmer?