Skip to content

Instantly share code, notes, and snippets.

@EgorBo
Last active July 18, 2021 12:21
Show Gist options
  • Save EgorBo/a3ac2b1f5c6e182acdd5f5d43c8335ec to your computer and use it in GitHub Desktop.
Save EgorBo/a3ac2b1f5c6e182acdd5f5d43c8335ec to your computer and use it in GitHub Desktop.
TypeChecks.cs
using BenchmarkDotNet.Attributes;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Running;
public class Program
{
static void Main(string[] args)
{
BenchmarkSwitcher.FromTypes(new[] { typeof(TypeChecks) }).Run(args);
}
}
public class BaseClass
{
[MethodImpl(MethodImplOptions.NoInlining)]
public virtual void DoWork() { }
}
public class Subclass : BaseClass
{
[MethodImpl(MethodImplOptions.NoInlining)]
public override void DoWork() { }
}
public class TypeChecks
{
private static object BaseClassInstance = new BaseClass();
private static object SubclassInstance = new Subclass();
private static object WrongInstance = new Program();
public IEnumerable<object> TestObjects()
{
yield return null;
yield return BaseClassInstance;
yield return SubclassInstance;
yield return WrongInstance;
}
[Benchmark]
[ArgumentsSource(nameof(TestObjects))]
public bool IsBaseClass(object o) => o is BaseClass;
[Benchmark]
[ArgumentsSource(nameof(TestObjects))]
public void CallDoWork(object o)
{
if (o is BaseClass bc)
{
bc.DoWork();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment