Skip to content

Instantly share code, notes, and snippets.

@dbolkensteyn
Created July 21, 2015 13:48
Show Gist options
  • Save dbolkensteyn/0ac2cc784069eb1526e7 to your computer and use it in GitHub Desktop.
Save dbolkensteyn/0ac2cc784069eb1526e7 to your computer and use it in GitHub Desktop.
// Suggested rule: warn on casts from interfaces to concrete types
using System;
namespace VS2013ConsoleApplication1.RoslynRule_samples
{
public interface IMyInterface
{
void DoStuff();
}
public class MyClass1 : IMyInterface
{
public int Data { get { return new Random().Next(); } }
public void DoStuff()
{
// TODO...
}
}
public static class DowncastExampleProgram
{
static void EntryPoint()
{
IMyInterface interfaceRef = FindInterfaceInstanceFromSomewhere();
// Worst-case: hard cast to a concrete type.
// Hard-codes the assumption that there is only one implementation
// of the interface -> fragile; causes maintenance issue.
// It also suggests that the IMyInterface abstraction is
// incomplete or incorrect: the caller is having to downcast to get
// data because it isn't on the interface.
MyClass1 class1 = (MyClass1)interfaceRef;
int privateData = class1.Data;
// 2. Slightly less bad version: at least it won't fail at runtime
class1 = interfaceRef as MyClass1;
if (class1 != null)
{
// ...
}
// Notes: you might validly want to downcast to a concrete
// type in a unit test. Also, casting to another interface is generally
// ok as a way of checking whether a behaviour is supported.
}
private static IMyInterface FindInterfaceInstanceFromSomewhere()
{
return new MyClass1();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment