String Performance Tip: Verifying if an Object is a String

There are two primary methods to confirm whether an object is a string. Here is an example of both:

if (obj is string)
{
    return obj.ToString();
}

Or use pattern matching

if (obj is string value)
{
    return value;
}

Benchmark Results

As indicated by these results, utilizing the first method mentioned above to check whether an object is a string is 1.17 times more performant than using pattern matching.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be reproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a Reply