<!DOCTYPE html>
<!--[if IE 6]>
<html id="ie6" lang="en-US">
<![endif]-->
<!--[if IE 7]>
<html id="ie7" lang="en-US">
<![endif]-->
<!--[if IE 8]>
<html id="ie8" lang="en-US">
<![endif]-->
<!--[if !(IE 6) & !(IE 7) & !(IE 8)]><!-->
<html lang="en-US">
<!--<![endif]-->
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>
Defaults in C# 4.0 Method Parameters | DevBlog	</title>
<link rel="profile" href="https://gmpg.org/xfn/11" />
<link rel="stylesheet" type="text/css" media="all" href="http://www.devblog.com/wp-content/themes/twentyeleven/style.css?ver=20230808" />
<link rel="pingback" href="http://www.devblog.com/xmlrpc.php">
<!--[if lt IE 9]>
<script src="http://www.devblog.com/wp-content/themes/twentyeleven/js/html5.js?ver=3.7.0" type="text/javascript"></script>
<![endif]-->
<link rel='dns-prefetch' href='//s.w.org' />
<link rel='dns-prefetch' href='//v0.wordpress.com' />
<link rel="alternate" type="application/rss+xml" title="DevBlog &raquo; Feed" href="http://www.devblog.com/feed" />
<link rel="alternate" type="application/rss+xml" title="DevBlog &raquo; Comments Feed" href="http://www.devblog.com/comments/feed" />
		<script type="text/javascript">
			window._wpemojiSettings = {"baseUrl":"https:\/\/s.w.org\/images\/core\/emoji\/13.0.1\/72x72\/","ext":".png","svgUrl":"https:\/\/s.w.org\/images\/core\/emoji\/13.0.1\/svg\/","svgExt":".svg","source":{"concatemoji":"http:\/\/www.devblog.com\/wp-includes\/js\/wp-emoji-release.min.js?ver=5.6.14"}};
			!function(e,a,t){var n,r,o,i=a.createElement("canvas"),p=i.getContext&&i.getContext("2d");function s(e,t){var a=String.fromCharCode;p.clearRect(0,0,i.width,i.height),p.fillText(a.apply(this,e),0,0);e=i.toDataURL();return p.clearRect(0,0,i.width,i.height),p.fillText(a.apply(this,t),0,0),e===i.toDataURL()}function c(e){var t=a.createElement("script");t.src=e,t.defer=t.type="text/javascript",a.getElementsByTagName("head")[0].appendChild(t)}for(o=Array("flag","emoji"),t.supports={everything:!0,everythingExceptFlag:!0},r=0;r<o.length;r++)t.supports[o[r]]=function(e){if(!p||!p.fillText)return!1;switch(p.textBaseline="top",p.font="600 32px Arial",e){case"flag":return s([127987,65039,8205,9895,65039],[127987,65039,8203,9895,65039])?!1:!s([55356,56826,55356,56819],[55356,56826,8203,55356,56819])&&!s([55356,57332,56128,56423,56128,56418,56128,56421,56128,56430,56128,56423,56128,56447],[55356,57332,8203,56128,56423,8203,56128,56418,8203,56128,56421,8203,56128,56430,8203,56128,56423,8203,56128,56447]);case"emoji":return!s([55357,56424,8205,55356,57212],[55357,56424,8203,55356,57212])}return!1}(o[r]),t.supports.everything=t.supports.everything&&t.supports[o[r]],"flag"!==o[r]&&(t.supports.everythingExceptFlag=t.supports.everythingExceptFlag&&t.supports[o[r]]);t.supports.everythingExceptFlag=t.supports.everythingExceptFlag&&!t.supports.flag,t.DOMReady=!1,t.readyCallback=function(){t.DOMReady=!0},t.supports.everything||(n=function(){t.readyCallback()},a.addEventListener?(a.addEventListener("DOMContentLoaded",n,!1),e.addEventListener("load",n,!1)):(e.attachEvent("onload",n),a.attachEvent("onreadystatechange",function(){"complete"===a.readyState&&t.readyCallback()})),(n=t.source||{}).concatemoji?c(n.concatemoji):n.wpemoji&&n.twemoji&&(c(n.twemoji),c(n.wpemoji)))}(window,document,window._wpemojiSettings);
		</script>
		<style type="text/css">
img.wp-smiley,
img.emoji {
	display: inline !important;
	border: none !important;
	box-shadow: none !important;
	height: 1em !important;
	width: 1em !important;
	margin: 0 .07em !important;
	vertical-align: -0.1em !important;
	background: none !important;
	padding: 0 !important;
}
</style>
	<link rel='stylesheet' id='wp-block-library-css'  href='http://www.devblog.com/wp-includes/css/dist/block-library/style.min.css?ver=5.6.14' type='text/css' media='all' />
<style id='wp-block-library-inline-css' type='text/css'>
.has-text-align-justify{text-align:justify;}
</style>
<link rel='stylesheet' id='wp-block-library-theme-css'  href='http://www.devblog.com/wp-includes/css/dist/block-library/theme.min.css?ver=5.6.14' type='text/css' media='all' />
<link rel='stylesheet' id='twentyeleven-block-style-css'  href='http://www.devblog.com/wp-content/themes/twentyeleven/blocks.css?ver=20230122' type='text/css' media='all' />
<link rel='stylesheet' id='jetpack_css-css'  href='http://www.devblog.com/wp-content/plugins/jetpack/css/jetpack.css?ver=9.3.4' type='text/css' media='all' />
<link rel="https://api.w.org/" href="http://www.devblog.com/wp-json/" /><link rel="alternate" type="application/json" href="http://www.devblog.com/wp-json/wp/v2/posts/181" /><link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://www.devblog.com/xmlrpc.php?rsd" />
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://www.devblog.com/wp-includes/wlwmanifest.xml" /> 
<meta name="generator" content="WordPress 5.6.14" />
<link rel="canonical" href="http://www.devblog.com/archives/181" />
<link rel='shortlink' href='https://wp.me/p83Rfx-2V' />
<link rel="alternate" type="application/json+oembed" href="http://www.devblog.com/wp-json/oembed/1.0/embed?url=http%3A%2F%2Fwww.devblog.com%2Farchives%2F181" />
<link rel="alternate" type="text/xml+oembed" href="http://www.devblog.com/wp-json/oembed/1.0/embed?url=http%3A%2F%2Fwww.devblog.com%2Farchives%2F181&#038;format=xml" />
<style type='text/css'>img#wpstats{display:none}</style><style type="text/css" id="custom-background-css">
body.custom-background { background-color: #333333; }
</style>
	
<!-- Jetpack Open Graph Tags -->
<meta property="og:type" content="article" />
<meta property="og:title" content="Defaults in C# 4.0 Method Parameters" />
<meta property="og:url" content="http://www.devblog.com/archives/181" />
<meta property="og:description" content="C# 4.0 was released in April 11, 2010. By that point, C# was 8 years old and there were A LOT of developers out there that knew C# already and didn’t pay much attention to the changes and didn’t in…" />
<meta property="article:published_time" content="2014-02-11T13:00:00+00:00" />
<meta property="article:modified_time" content="2014-02-11T23:37:02+00:00" />
<meta property="og:site_name" content="DevBlog" />
<meta property="og:image" content="https://s0.wp.com/i/blank.jpg" />
<meta property="og:locale" content="en_US" />
<meta name="twitter:text:title" content="Defaults in C# 4.0 Method Parameters" />
<meta name="twitter:card" content="summary" />

<!-- End Jetpack Open Graph Tags -->
</head>

<body class="post-template-default single single-post postid-181 single-format-standard custom-background wp-embed-responsive single-author singular two-column right-sidebar">
<div class="skip-link"><a class="assistive-text" href="#content">Skip to primary content</a></div><div id="page" class="hfeed">
	<header id="branding">
			<hgroup>
				<h1 id="site-title"><span><a href="http://www.devblog.com/" rel="home">DevBlog</a></span></h1>
				<h2 id="site-description">Musings on Software Development</h2>
			</hgroup>

						<a href="http://www.devblog.com/">
									<img src="http://devblog.com/wp-content/uploads/2014/01/cropped-RocketForDevBlog.jpg" width="1000" height="288" alt="DevBlog" />
								</a>
			
									<form method="get" id="searchform" action="http://www.devblog.com/">
		<label for="s" class="assistive-text">Search</label>
		<input type="text" class="field" name="s" id="s" placeholder="Search" />
		<input type="submit" class="submit" name="submit" id="searchsubmit" value="Search" />
	</form>
			
			<nav id="access">
				<h3 class="assistive-text">Main menu</h3>
				<div class="menu-main-container"><ul id="menu-main" class="menu"><li id="menu-item-153" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-153"><a href="http://devblog.com">Home</a></li>
<li id="menu-item-227" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-227"><a href="http://www.devblog.com/links">Links</a></li>
<li id="menu-item-152" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-152"><a href="http://www.devblog.com/about">About</a></li>
</ul></div>			</nav><!-- #access -->
	</header><!-- #branding -->


	<div id="main">

		<div id="primary">
			<div id="content" role="main">

				
					<nav id="nav-single">
						<h3 class="assistive-text">Post navigation</h3>
						<span class="nav-previous"><a href="http://www.devblog.com/archives/171" rel="prev"><span class="meta-nav">&larr;</span> Previous</a></span>
						<span class="nav-next"><a href="http://www.devblog.com/archives/190" rel="next">Next <span class="meta-nav">&rarr;</span></a></span>
					</nav><!-- #nav-single -->

					
<article id="post-181" class="post-181 post type-post status-publish format-standard hentry category-c category-tips-and-tricks tag-c tag-tips-and-tricks">
	<header class="entry-header">
		<h1 class="entry-title">Defaults in C# 4.0 Method Parameters</h1>

				<div class="entry-meta">
			<span class="sep">Posted on </span><a href="http://www.devblog.com/archives/181" title="8:00 am" rel="bookmark"><time class="entry-date" datetime="2014-02-11T08:00:00-05:00">February 11, 2014</time></a><span class="by-author"> <span class="sep"> by </span> <span class="author vcard"><a class="url fn n" href="http://www.devblog.com/archives/author/admin" title="View all posts by Curt" rel="author">Curt</a></span></span>		</div><!-- .entry-meta -->
			</header><!-- .entry-header -->

	<div class="entry-content">
		<p><a href="http://en.wikipedia.org/wiki/C_Sharp_4.0" target="_blank">C# 4.0</a> was released in April 11, 2010. By that point, C# was 8 years old and there were A LOT of developers out there that knew C# already and didn’t pay much attention to the changes and didn’t incorporate them into their current code. Many were able to keep chugging along happily doing what they had been doing without having <a href="http://msdn.microsoft.com/en-us/magazine/ff796223.aspx" target="_blank">to learn about the new features.</a></p>
<p>That’s too bad.</p>
<p>One of my favorite, 4.0 additions is named-arguments and optional-parameters. I think they are my favorites because of my stint as a Visual Basic programmer during my time between PowerBuilder and C#. You got used to not supplying parameters if you didn’t care to pass them or didn’t need them.</p>
<p>You can easily tell when a developer doesn’t know about this feature too. They tend to have a lot of overloading of a method that essentially hides parameters. And, they make calls to variants of the methods when they want to have defaults and not supply them. Or, they don’t want to have to supply them everywhere.</p>
<p>Their code will look something like this:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Broadcast(<span class="kwrd">string</span> group, <span class="kwrd">int</span> unitId) { . . . }

<span class="kwrd">public</span> <span class="kwrd">void</span> Broadcast(<span class="kwrd">string</span> group) { Broadcast(group, 5); }

<span class="kwrd">public</span> <span class="kwrd">void</span> Broadcast() { Broadcast(“Red Leader”); }</pre>
<p>From above, you can see that the first method takes two parameters. If this were the only method, you’d have to supply defaults everywhere. So, in the event that you just want to pass the group and always default to 5 in the unitId when you do, you could just call the second routine. Or, if you want to default both parameters, you could call the third variation, which calls the second, which then calls the first. That’s a lot of pushing and popping on the stack just to have defaults. </p>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
</p>
<p>After C# 4.0, these three methods can be collapsed into just this one method by simply using defaults. Here’s what it looks like</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Broadcaster
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> Broadcast(<span class="kwrd">string</span> group = <span class="str">"Red Leader"</span>,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="kwrd">int</span> unitId = 5)
    {
        Console.WriteLine(<span class="str">"This is {0} {1}"</span>, group, unitId);
    }
}

<span class="kwrd">class</span> Program
{
    <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
    {
        Broadcaster.Broadcast();
        Broadcaster.Broadcast(group: <span class="str">"Blue Leader"</span>);
        Broadcaster.Broadcast(unitId: 2);
    }
}</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p>So, if you just wanted to supply a different unitId, you simply pass in a unitId: 6 in the method call. The group would default, and the effect is as if you called the method with the parameters “Red Leader” and 5.</p>
<p>Defaults make these sorts of libraries much leaner to write. </p>
<p>I hope this helps you.</p>
			</div><!-- .entry-content -->

	<footer class="entry-meta">
		This entry was posted in <a href="http://www.devblog.com/archives/category/my-blog/c" rel="category tag">C#</a>, <a href="http://www.devblog.com/archives/category/my-blog/tips-and-tricks" rel="category tag">Tips and Tricks</a> and tagged <a href="http://www.devblog.com/archives/tag/c" rel="tag">C#</a>, <a href="http://www.devblog.com/archives/tag/tips-and-tricks" rel="tag">Tips and Tricks</a> by <a href="http://www.devblog.com/archives/author/admin">Curt</a>. Bookmark the <a href="http://www.devblog.com/archives/181" title="Permalink to Defaults in C# 4.0 Method Parameters" rel="bookmark">permalink</a>.
		
			</footer><!-- .entry-meta -->
</article><!-- #post-181 -->

						<div id="comments">
	
	
	
	
</div><!-- #comments -->

				
			</div><!-- #content -->
		</div><!-- #primary -->


	</div><!-- #main -->

	<footer id="colophon">

			

			<div id="site-generator">
												<a href="https://wordpress.org/" class="imprint" title="Semantic Personal Publishing Platform">
					Proudly powered by WordPress				</a>
			</div>
	</footer><!-- #colophon -->
</div><!-- #page -->

<script type='text/javascript' src='http://www.devblog.com/wp-includes/js/comment-reply.min.js?ver=5.6.14' id='comment-reply-js'></script>
<script type='text/javascript' src='http://www.devblog.com/wp-includes/js/wp-embed.min.js?ver=5.6.14' id='wp-embed-js'></script>
<script src='https://stats.wp.com/e-202429.js' defer></script>
<script>
	_stq = window._stq || [];
	_stq.push([ 'view', {v:'ext',j:'1:9.3.4',blog:'119130367',post:'181',tz:'-4',srv:'www.devblog.com'} ]);
	_stq.push([ 'clickTrackerInit', '119130367', '181' ]);
</script>

</body>
</html>
