Code It Any Way You Want: Comparison of Passing Parameters in Methods

There are several ways to pass a parameter into a method. Here is an example of a conventional approach to passing parameters into a method:

private static string MethodParams(string text, DateTime dateTime, Person person)
{
    return $"{text}:{dateTime}:{person}";
}

You can also utilize the in operator. The in keyword is employed to indicate that an argument is passed by reference but is read-only within the method. It is primarily employed in the context of passing parameters to methods. Here is an example:

private static string MethodParams(string text, in DateTime dateTime, Person person)
{
    return $"{text}:{dateTime}:{person}";
}

Lastly, you can also use ref readonly as shown in this example:

private static string MethodParams(string text, ref readonly DateTime dateTime, Person person)
{
    return $"{text}:{dateTime}:{person}";
}

I was curious about which of these methods is more performant.

Benchmark Results

As you can see in these results, all three of these methods of passing a parameter exhibit similar performance. Additionally, for these tests, all methods allocate around 8,400 bytes.

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

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

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 preproduced 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 comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.