<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>YTechie.com &#187; .net</title>
	<atom:link href="http://www.ytechie.com/category/net/feed" rel="self" type="application/rss+xml" />
	<link>http://www.ytechie.com</link>
	<description>Productive software development using ASP.NET, C#, Adobe Flex, and other technologies and tools.</description>
	<lastBuildDate>Fri, 06 Nov 2009 21:16:21 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Understanding LINQ and LINQ to SQL (and EF)</title>
		<link>http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html</link>
		<comments>http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html#comments</comments>
		<pubDate>Thu, 17 Sep 2009 15:17:44 +0000</pubDate>
		<dc:creator>superjason</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[entity framwork]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html</guid>
		<description><![CDATA[Back to basics for this post. Developers often throw around the word LINQ when talking about a number of different technologies. Now that I have been comfortably using a wide variety of LINQ technologies for a fair amount of time, I’m now able to convey some of the key differences that are critical to using [...]]]></description>
			<content:encoded><![CDATA[<p>Back to basics for this post. Developers often throw around the word LINQ when talking about a number of different technologies. Now that I have been comfortably using a wide variety of LINQ technologies for a fair amount of time, I’m now able to convey some of the key differences that are critical to using LINQ technologies efficiently. I’m also using this as a foundation and reference for some exciting upcoming posts.</p>
<p>The first key point is to know what the heck LINQ is. LINQ itself is a number of separate features. One of these key features is being able to write SQL-like syntax (query syntax) in your code. At a basic level, that’s all you need to know for now.</p>
<p><strong>LINQ (to objects)</strong></p>
<p>First, we’re going to talk about LINQ to objects, which I typically just refer to as LINQ (possibly making the matter more confusing). It has absolutely nothing to do with SQL Server, Oracle, or any other kind of relational database. I’m talking about LINQ to objects, because I think that understanding it and contrasting it with LINQ to SQL is critical to understanding both.</p>
<p>For a moment, forget that LINQ exists. Let’s say that you wanted to filter a list of names, to only get names that start with the letter “J”. You could write the following “utility” function: (if you don’t understand <a href="http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html">“yield return”, see this post on that topic</a>).</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:74dcd1eb-c170-4d76-b6e8-441fc9f40dba" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public static IEnumerable&lt;string&gt; GetNamesStartingWithJ(IEnumerable&lt;string&gt; names)
{
    foreach(var name in names)
        if(name.StartsWith("J"))
            yield return name;
}</pre>
</div>
<p>A new feature in C# introduced in .NET 3.0, is a concept known as an extension method. This lets us turn my handy dandy static utility method into a method that can be called on a list of names. By changing the signature to this:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:b27c9cbc-7f0a-4fb5-be05-8f5946380254" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public static IEnumerable&lt;string&gt; GetNamesStartingWithJ(this IEnumerable&lt;string&gt; names)</pre>
</div>
<p>I can then call it like this (Sweet!):</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:9b70c490-45ef-40a4-903b-4cbd3b3470ed" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">var myListOfNames = new List&lt;T&gt; {"Abe", "Jack", "Jason"};
var jNames = myListOfNames.GetNamesStartingWithJ();</pre>
</div>
<p>We haven’t even talked about LINQ yet, but we’ve basically reinvented a portion of it. As an exercise for the reader, think about how you could use a Lambda parameter to pass in a filter criteria to create a &quot;.Where” method. All the pieces are in place to re-create this form of LINQ yourself.</p>
<p>One actual new feature for LINQ is known as query syntax. Basically, it gives us an alternative way to write our query. It makes the code look more like SQL, and less like a long chain of extension methods.</p>
<p>Lambda Syntax:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:a76b3655-6a72-4fa3-b147-38bfd8dedf80" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">var uppercaseJNames = names.Where(name =&gt; name.StartsWith("J")).Select(name =&gt; name.ToUpper());</pre>
</div>
<p>Query Syntax (same query):</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:7e10587a-ba5f-4062-bba8-cab816b7eb3e" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">var uppercaseJNames = from name in names
	where name.StartsWith("J")
	select name.ToUpper();</pre>
</div>
<p>In both of those examples, the exact same operations are occurring, and you get the result. The one you choose will most likely come down to personal preference. It’s also worth noting that some of the extension methods provided out of the box are not available in query syntax. You can either avoid the query syntax in those cases, or use a hybrid approach.</p>
<p><strong>How is LINQ to SQL (and Entity Framework, etc) Different?</strong></p>
<p>Now, I hope you understand that there isn’t really any magic going on in LINQ. Microsoft has simply given us a new set of easy to use tools that make working with sets a breeze.</p>
<p>LINQ to SQL is a different matter. Instead of executing code, you’re building an expression. An expression is simply a “picture” of what you’re trying to accomplish. It can interpreted in many different ways. To understand the underlying technology, you’ll have to read up on expression trees, which I’m intentionally keeping outside the scope of this post.</p>
<p>If we have a “picture” of a query, what happens to it when we want to “run” it? LINQ to SQL, Entity Framework, and other LINQ implementations look at your query, and basically translate it into something else. How about an example?:</p>
<p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:fc8658fb-f565-47dc-af0c-f5c4007c3a89" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">//Query Syntax
var deviceIds = from device in Devices
where device.Type == "I"
select device.DeviceId

//Lambda Sytax (extension methods)
var deviceIds = Devices
   .Where (device =&gt; (device.Type == "I"))
   .Select (device =&gt; device.DeviceId)

//SQL
SELECT [t0].[DeviceId]
FROM [Devices] AS [t0]
WHERE [t0].[Type] = "I"</pre>
</div>
<p>I’ve provided the query syntax and the lambda syntax. At the bottom is the resulting translation into a SQL statement.</p>
<p>In this last example, I’ll try to make it clear that your code is simply interpreted and translated:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:a87dc611-83a7-4e29-ad97-f2b3ecff5f57" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">//Query Syntax:
from device in Devices
where device.Type != null
select device.DeviceId

//SQL Syntax:
SELECT [t0].[DeviceId]
FROM [Devices] AS [t0]
WHERE [t0].[Type] IS NOT NULL</pre>
</div>
<p>Notice that the C# operator “!=” translates in SQL to “IS NOT NULL”. This was handled automatically for us. Our expression did NOT get back all the rows and apply a conditional to it.</p>
<p>Why is this important? To use either technology effectively, you have to understand that when you’re working with objects, it’s simply a chain of methods, and often behaves as you would expect. When working with LINQ to SQL (or a related technology), the expression is evaluated, and might not execute like you expected.</p>
<p>Understanding the internal workings of these technologies will let us fully take advantage of all the wonderful features it has to offer. In upcoming posts, I’ll be warning you of some potential pitfalls related to how your queries are interpreted and translated. I’ll also be showing you how to get significant performance gains by using LINQ to SQL or Entity Framework efficiently (over traditional SQL based solutions). I’ll also be showing you how I write LINQ queries to query an AutoCAD document!</p>
<p>Related Posts:</p>
<ul>
<li><a href="http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html">Using Yield Return for readability and performance</a></li>
<li><a href="http://www.ytechie.com/2008/06/using-var-to-simplify-code-and-avoid-redundancy.html">Using “var” to simplify code and avoid redundancy</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/09/understanding-linq-and-linq-to-sql-and-ef.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Delayed execution vs ToList() in LINQ Database Queries</title>
		<link>http://www.ytechie.com/2009/06/delayed-execution-vs-tolist-in-linq-database-queries.html</link>
		<comments>http://www.ytechie.com/2009/06/delayed-execution-vs-tolist-in-linq-database-queries.html#comments</comments>
		<pubDate>Tue, 23 Jun 2009 16:46:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[entity framwork]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/06/delayed-execution-vs-tolist-in-linq-database-queries.html</guid>
		<description><![CDATA[LINQ to SQL and Entity framework allow us to build a query, which gets translated into an expression tree, and executed once the full query is built. The beauty is that we can build up a query using multiple expressions and Lambdas, without actually querying the data. Since these types of queries are delay loaded, [...]]]></description>
			<content:encoded><![CDATA[<p>LINQ to SQL and Entity framework allow us to build a query, which gets translated into an expression tree, and executed once the full query is built. The beauty is that we can build up a query using multiple expressions and Lambdas, without actually querying the data. Since these types of queries are delay loaded, why not avoid executing them until the last possible moment? Read on to see why this is usually a bad idea.</p>
<p>First, let’s take a look the code for a repository method that builds a query, executes the query, and returns the results in a list:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:3a31321f-f9b9-4c17-91c2-43d838b3f22a" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public IEnumerable&lt;Cat&gt; FindAllCats()
{
	var query = from c in db.Cats
		select c;

	return query.ToList();
}</pre>
</div>
<p align="center"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Execute in Repository" border="0" alt="Execute in Repository" src="http://www.ytechie.com/post-images/2009/06/image1.png" width="486" height="142" /> </p>
<p>The “ToList” is forcing the IQueryable&lt;Cat&gt; query to execute and put the results in a list <strong>immediately</strong>. However, we know that IQueryable&lt;T&gt; inherits from IEnumerable&lt;T&gt;, so what happens if we avoid the list creation completely?</p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:10d24797-5a70-435a-85bc-c076fe3c457b" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public IEnumerable&lt;Cat&gt; FindAllCats()
{
	var query = from c in db.Cats
		select c;

	return query;
}</pre>
</div>
<p align="center"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Execute in UI" border="0" alt="Execute in UI" src="http://www.ytechie.com/post-images/2009/06/image2.png" width="486" height="142" /></p>
<p align="left">In this scenario, our method is returning the same interface, but the underlying type is now a LINQ database iterator instead of a List&lt;T&gt;.</p>
<p><strong>Delaying execution can lead to</strong> <strong><em>multiple</em></strong> <strong>executions</strong></p>
<p>If the code is not explicitly putting the results into a list, we’re actually passing back a form of an iterator. This works great if we only need to execute the query once. However, if we iterate through the list more than once, <strong>we actually end up executing our query multiple times</strong>. This can obviously lead to poor performance.</p>
<p>If you’re writing fast queries, you may not even notice if they’re being called too many times. However, there may be a worse problem lurking in your code. <strong>Each time you iterate through the enumerator, you’re getting a different set of objects</strong>. The same query is being made with the same results, but the objects are re-built each time. This leads to objects that are <strong>equivalent, but not the same</strong>. For example, you may get back Cat objects with the names “Bill” and “Ted”, but if you actually check them for equality using “==”, they will not be the same object <strong>instance</strong>. <font color="#ff0000"><strong>Correction: Scott points out in the comments that this isn’t necessarily the case. Keep in mind that it can still occur if projecting types and not working with the original objects.</strong></font></p>
<p><strong>Delaying execution may mean you no longer have a database connection when attempting to execute the query</strong></p>
</p>
<p>If you delegate the task of initiating your query to another layer, you better be sure that the database connection is still around, and is in a queryable state. If you’re using the standard repository pattern and a short-lived database connection pattern, you may quickly run into problems when you try to iterate through the results of the enumerator you receive from your repository layer.</p>
<p><strong>Conclusion</strong></p>
<p>If you’re thinking about moving the execution of your queries to another layer, make sure you understand the consequences. You’ll need to weigh those consequences against the tiny benefit that you’ll receive from the delayed execution. There may be cases where delaying the execution or possibly avoiding it completely will improve your application, but those are probably very rare cases.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/06/delayed-execution-vs-tolist-in-linq-database-queries.html/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Common Pitfalls when working with DateTime&#8217;s</title>
		<link>http://www.ytechie.com/2009/06/common-pitfalls-when-working-with-datetimes.html</link>
		<comments>http://www.ytechie.com/2009/06/common-pitfalls-when-working-with-datetimes.html#comments</comments>
		<pubDate>Tue, 02 Jun 2009 19:05:49 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/06/common-pitfalls-when-working-with-datetimes.html</guid>
		<description><![CDATA[In .NET, the DateTime structure provides us wonderful functionality, but this seemingly simple structure can cause a lot of headaches if you don’t fully understand how to use it properly.
 
Understand the terminology
First, UTC, GMT, and even Zulu time are all the same thing. They’re basically a universal time clock that is not subject to [...]]]></description>
			<content:encoded><![CDATA[<p>In .NET, the <a href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/system.datetime.aspx?referer=');">DateTime</a> structure provides us wonderful functionality, but this seemingly simple structure can cause a lot of headaches if you don’t fully understand how to use it properly.</p>
<p align="center"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Clock" border="0" alt="Clock" src="http://www.ytechie.com/post-images/2009/06/clock.jpg" width="244" height="163" /> </p>
<p><strong>Understand the terminology</strong></p>
<p>First, UTC, GMT, and even Zulu time are all the same thing. They’re basically a universal time clock that is not subject to changes in time zones or time changes. Each tick of the universal clock represents a moment in our perception of time. </p>
<p><strong>Use UTC as long as possible</strong></p>
<p><strong>UTC</strong> is very useful when developing software because it removes the need to know where the time was from, or where it’s going to be used. We don’t even care <em>when</em> it was from, or <em>when</em> we’re displaying it. You can think of your <strong>local</strong> clock as a view of the time right now, where you are. It has already taken into account the time zone and daylight savings time.</p>
<p>These properties of your local clock suggest that we should always convert from the local clock to universal time as early as possible when accepting user input, and convert it back to the users time only when displaying it. This is a simple, easy to use pattern that may be enough to avoid some of the potential problems that other projects face. This pattern will give you the ability to cope with time changes and time zones much more easily.</p>
<p>Converting between local time and UTC is pretty easy. <a href="http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx?referer=');">ToLocalTime</a> will convert from universal time to local time. <a href="http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx?referer=');">ToUniversalTime</a> will convert to UTC. Just be aware that these methods have a certain amount of logic in them that only has the rules that were in effect when they were written. They are not perfect for all scenarios. You’ll also want to take a look at the <a href="http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx?referer=');">Kind</a> property, which affects which conversions you can perform, as well as providing a nice way to keep track of whether or not he time has been adjusted to UTC.</p>
<p><strong>Daylight Savings Time &amp; Time Changes</strong></p>
<p>Every year in many parts of the world, the time changes. Apparently the idea is to save gobs of money by using the sunlight more efficiently instead of using artificial lights. Unfortunately, this really sucks for software developers.</p>
<p>I used to write software for manufacturing facilities that would run during a time change. If you have software that records and time-sensitive data during a time change, your software had better be prepared to handle it the fact that one hour is skipped, and another is repeated. Storing the data in UTC solves part of the problem. Unfortunately, when you try to display the data you’ll have an hour of missing data, and a hour with overlapping data. <strong>You may have to design your user interface to deal with this</strong>.</p>
<p><strong>Fixed-time Appointments</strong></p>
<p>Unfortunately, UTC doesn’t solve all of our time offset problems. Let’s say that you have an appointment that you’re scheduling for a future date that occurs when DST is in effect, but it’s not in effect right now. You choose 5:00am for your appointment time. Your application happily converts the time to UTC, and the reverse process expectedly yields the same result. The problem is, the time offset when the appointment occurs will be different than it is now. Daylight savings for the central time zone for example, switches between and offset of –5 and –6. This diagram attempts to visualize:</p>
<p align="center">&#160;<img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="DST DateTime Diagram" border="0" alt="DST DateTime Diagram" src="http://www.ytechie.com/post-images/2009/06/image.png" width="476" height="260" /> </p>
<p>What we want to store is the fact that our appointment occurs at <strong>5:00am local time</strong>. If we simply store the information as UTC, we’re losing this additional information. When we switch to <strong>non-DST</strong> time and use our current time adjustment of <strong>–6 hours</strong>, our appointment now occurs at <strong>4:00am</strong>.</p>
<p>If you’re writing an application that stores fixed-time appointments as well as appointments that are designed to have even intervals (exactly 1 month apart, etc) or occur in a different time zone or DST, you’ll need to store an additional flag with the event so you can make the determination if it needs to be adjusted.</p>
<p><strong>Conclusion</strong></p>
<p>Times can be complicated depending on the requirements of your project. It would be unwise to work these problems out toward the end of a project, because the consistency of usage can’t be guaranteed. Do yourself a favor and plan ahead for these issues, and it will be much easier.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/06/common-pitfalls-when-working-with-datetimes.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Speaking at Day of .NET at Fox Valley Tech</title>
		<link>http://www.ytechie.com/2009/04/speaking-at-day-of-net-at-fox-valley-tech.html</link>
		<comments>http://www.ytechie.com/2009/04/speaking-at-day-of-net-at-fox-valley-tech.html#comments</comments>
		<pubDate>Tue, 28 Apr 2009 14:54:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/04/speaking-at-day-of-net-at-fox-valley-tech.html</guid>
		<description><![CDATA[If you’re interested in hearing about writing practical unit tests in .NET, I’ll be speaking at the Fox Valley .NET user group “Day of .NET” event May 9th! Here is the synopsis for your reading pleasure:
Want to learn how to write good automated unit tests that are beneficial both to the product/customer and to you [...]]]></description>
			<content:encoded><![CDATA[<p>If you’re interested in hearing about writing practical unit tests in .NET, I’ll be speaking at the <a href="http://fvnug.org" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/fvnug.org?referer=');">Fox Valley .NET user group</a> <a href="http://fvnug.org/dnn/DayOfNet/Schedule/tabid/62/Default.aspx" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/fvnug.org/dnn/DayOfNet/Schedule/tabid/62/Default.aspx?referer=');">“Day of .NET” event</a> May 9th! Here is the synopsis for your reading pleasure:</p>
<blockquote><p>Want to learn how to write good automated unit tests that are beneficial both to the product/customer and to you as a developer? See an overview of the mechanics of unit testing including the tools and frameworks available. You&#8217;ll see examples of how to test existing code, but you&#8217;ll also see practical examples of how seemingly un-testable code can be designed so that it can be tested with ease. Learn how test driven development and refactoring will improve the readability of your code, minimize debugging, and speed up development.</p>
</blockquote>
<p><a href="http://fvnug.org" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/fvnug.org?referer=');"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://www.ytechie.com/post-images/2009/04/image5.png" width="490" height="79" /></a> </p>
<p>If you’re anywhere near the Northeast Wisconsin area, stop in. It’s free!</p>
<p>I’ll be publishing both the presentation and a supporting 25+ page paper shortly, so make sure you’re <a href="http://feedproxy.google.com/Ytechie" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/feedproxy.google.com/Ytechie?referer=');">subscribed to my feed</a>.</p>
<p><a href="http://www.fvtc.edu/public/" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/www.fvtc.edu/public/?referer=');">Fox Valley Tech</a> is located at:     <br /><a href="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=1825+N.+Bluemound+Drive,+Appleton+WI&amp;sll=37.0625,-95.677068&amp;sspn=1.468445,2.771301&amp;ie=UTF8&amp;z=15&amp;msa=0&amp;msid=107741674408312530799.000001120068a94c2e438" rel="nofollow" onclick="pageTracker._trackPageview('/outgoing/maps.google.com/maps?f=q_amp_source=s_q_amp_hl=en_amp_geocode=_amp_q=1825+N.+Bluemound+Drive_+Appleton+WI_amp_sll=37.0625_-95.677068_amp_sspn=1.468445_2.771301_amp_ie=UTF8_amp_z=15_amp_msa=0_amp_msid=107741674408312530799.000001120068a94c2e438&amp;referer=');">1825 N. Bluemound</a>     <br />Appleton, WI 54912</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/04/speaking-at-day-of-net-at-fox-valley-tech.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>int inherits from object? An investigation into how.</title>
		<link>http://www.ytechie.com/2009/04/int-inherits-from-object-an-investigation-into-how.html</link>
		<comments>http://www.ytechie.com/2009/04/int-inherits-from-object-an-investigation-into-how.html#comments</comments>
		<pubDate>Fri, 17 Apr 2009 18:39:47 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.net]]></category>

		<guid isPermaLink="false">http://www.ytechie.com/2009/04/int-inherits-from-object-an-investigation-into-how.html</guid>
		<description><![CDATA[I’ve began working with a study group which was formed to study for the .NET Framework Application Development certification exam (70-536). I’m eager to get certified because I think it helps fill-in knowledge gaps that I may not have necessarily took the time to focus on normally. One of the first things that came up [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve began working with a study group which was formed to study for the .NET Framework Application Development certification exam (70-536). I’m eager to get certified because I think it helps fill-in knowledge gaps that I may not have necessarily took the time to focus on normally. One of the first things that came up in our study group is the fact that <strong>int</strong>, which is an alias for <strong>System.Int32</strong>, derives from Sytem.ValueType, which, in turn, derives from <strong>System.Object</strong>. Let’s take a close look at what that actually means, and how it’s implemented.</p>
<p>When I first heard that <strong>int</strong> ultimately derived from Object, I didn’t believe it for a number of reasons:</p>
<ul>
<li>If you inherit from <strong>Object</strong>, that derived object IS an object </li>
<li>If <strong>int</strong> is a subclass of <strong>Object</strong>, then boxing isn’t necessary </li>
</ul>
<p>The truth is, my assumptions were not correct. The .NET team, for consistency sake, made all types fit nicely into the type hierarchy:</p>
<p align="center"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Object Hierarchy" border="0" alt="Object Hierarchy" src="http://www.ytechie.com/post-images/2009/04/image3.png" width="275" height="306" /> </p>
<p align="left">If the .NET team had built <strong>System.Int32</strong> to work like any other reference type, there would be clear performance issues. In reality, we need value types to be lean and mean. They are stored on the stack (instead of the heap for reference types). To do this, there is some internal “magic” going on that treats objects that inherit from ValueType differently. Behind the scenes it optimizes how they’re used to get the best of both worlds. If you try to inherit from ValueType, you’ll get a compiler error, because it is only exists for build-in value types.</p>
<p align="left">Of course we want our cake and we want to eat it too. There are often times when you want to use a value type in a method that takes an object as a parameter. To keep up the illusion that a value type is an object, the framework employs boxing. It effectively wraps the value type inside of an object.</p>
<p align="center"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Let me out, I&#39;m an object!" border="0" alt="Let me out, I&#39;m an object!" src="http://www.ytechie.com/post-images/2009/04/image4.png" width="283" height="269" /></p>
<p align="left">Take a look a the following code:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:51b1363f-2059-42fd-8c66-268d18130de3" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">public string GetObjectString(object obj)
{
    return obj.ToString();
}

[TestMethod]
public void IntAsObject_Boxing()
{
    var str = GetObjectString(4);
    Assert.AreEqual("4", str);
}</pre>
</div>
<p align="left">And look at the corresponding IL for the test method:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:8e0c58b8-4c00-4610-aa74-6f1b2f84be66" class="wlWriterEditableSmartContent">
<pre name="code" class="c#">IL_0001:  ldarg.0
IL_0002:  ldc.i4.4
IL_0003:  box        [mscorlib]System.Int32
IL_0008:  call       instance string _4_17_09_Boxing.UnitTest1::GetObjectString(object)
IL_000d:  stloc.0
IL_000e:  ldstr      "4"
IL_0013:  ldloc.0
IL_0014:  call       void [Microsoft.VisualStudio.QualityTools.UnitTestFramework]Microsoft.VisualStudio.TestTools.UnitTesting.Assert::AreEqual&lt;string&gt;(!!0, !!0)
IL_0019:  nop
IL_001a:  ret</pre>
</div>
<p align="left">Notice that boxing occurs on line 3. It’s using the IL “box” command to let you stay oblivious to the fact that there is some magic going on behind the scenes.</p>
<p align="left"><strong>Conclusion</strong></p>
<p align="left">The end result is that we have an integer, which is an object, but isn’t really, that needs to be wrapped inside of an object, which shouldn’t be necessary, but is because it is. <img src='http://www.ytechie.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p align="left">Does this really matter? Well, not really. For the most part you don’t need to know this. If you’re truly inquisitive and want to know what’s going on, you may find it interesting.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ytechie.com/2009/04/int-inherits-from-object-an-investigation-into-how.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
