<?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>MaxoTech Blog &#187; Programming</title>
	<atom:link href="http://maxotek.net/blog/category/programming/feed" rel="self" type="application/rss+xml" />
	<link>http://maxotek.net/blog</link>
	<description>Technology Blog</description>
	<lastBuildDate>Wed, 29 Jun 2011 07:44:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Reflector to the Rescue</title>
		<link>http://maxotek.net/blog/reflector-to-the-rescue-t306.html</link>
		<comments>http://maxotek.net/blog/reflector-to-the-rescue-t306.html#comments</comments>
		<pubDate>Tue, 06 Jul 2010 02:18:29 +0000</pubDate>
		<dc:creator>partho</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Decompiling]]></category>
		<category><![CDATA[Version Control]]></category>
		<category><![CDATA[Reflector]]></category>
		<category><![CDATA[Subversion]]></category>

		<guid isPermaLink="false">http://maxotek.net/blog/reflector-to-the-rescue-t306.html</guid>
		<description><![CDATA[I was trying to get a list of all un-versioned C# code files in my working copy. Some examples on the internet pointed to Windows Power Shell which is able to pipe the output of one command to another (kind of what we have in linux). The command was:- (svn stat) -match '^\?.*\.cs$' The following [...]]]></description>
			<content:encoded><![CDATA[<p>I was trying to get a list of all un-versioned C# code files in my working copy. Some examples on the internet pointed to Windows Power Shell which is able to pipe the output of one command to another (kind of what we have in linux).</p>
<p>The command was:-</p>
<pre><code>(svn stat) -match '^\?.*\.cs$'</code></pre>
<p>The following command gave a much cleaner output (just the full path of the files)</p>
<pre><code>(svn stat &quot;--no-ignore&quot;) -match '^\?.*\.cs$' -replace '^.\s+',''</code></pre>
<p>The next command deleted those files from the PC.</p>
<pre><code>(svn stat &quot;--no-ignore&quot;) -match '^\?.*\.cs$' -replace '^.\s+','' | rm</code></pre>
<p>I did not pay attention to what the command does and executed it. Net result was that my precious source codes were gone. I looked for the files in the recycle bin. But, being a command line program, it does not seem to use the recycle bin. Then I tried NTFS undelete which is able to restore files that were deleted ‘permanently’ too. What happens is that when you delete a file (SHIFT + DELETE, skipping the recycle bin), windows merely marks the space the file occupied in the disk as free. This is done for performance reasons (a delete operation would take time that is comparable to writing to a file, otherwise).</p>
<p>However, to my dismay, NTFS undelete was unable to find the file. Perhaps it was because of Windows 7 and it&#8217;s ways of handling different versions of a file.</p>
<p>It seemed like I would have to re-create the files again. But, then it occurred to me that reflector could come in handy. I had compiled the project previously. So, the debug directory had the compiled assemblies. I used reflector to get the source files back. Although not the exact as the original, the decompiled code was good enough for me to re-create the custom user-control.</p>
]]></content:encoded>
			<wfw:commentRss>http://maxotek.net/blog/reflector-to-the-rescue-t306.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Tutorial : Lesson 15 &#8211; Error Handling</title>
		<link>http://maxotek.net/blog/c-tutorial-lesson-15-error-handling-t54.html</link>
		<comments>http://maxotek.net/blog/c-tutorial-lesson-15-error-handling-t54.html#comments</comments>
		<pubDate>Thu, 25 Oct 2007 18:35:25 +0000</pubDate>
		<dc:creator>partho</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://maxotek.net/blog/?p=54</guid>
		<description><![CDATA[There are three types of errors that can occur in your application. These are:- Syntax Errors Runtime Errors or Exceptions Logical Errors Syntax errors occur due to ill-formed codes. The cause can be a misspelled keyword, improperly constructed statements, absence of punctuations, such as line terminators, etc. The resulting code cannot be until all of [...]]]></description>
			<content:encoded><![CDATA[<div class="tutnav"></div>
<p>There are three types of errors that can occur in your application. These are:-</p>
<ul>
<li>Syntax Errors</li>
<li>Runtime Errors or Exceptions</li>
<li>Logical Errors</li>
</ul>
<p><b>Syntax errors</b> occur due to ill-formed codes. The cause can be a misspelled keyword, improperly constructed statements, absence of punctuations, such as line terminators, etc. The resulting code cannot be until all of these errors are removed.</p>
<p>Example:-</p>
<p><img src="/images/blog/csharp_tut_lesson_15_syntax_error.png" /></p>
<p>In this case the keyword Class is misspelled as Clas. Notice how the Visual Studio IDE highlights the error even before compilation starts. This is possible because of background compiling which is utilized in almost all modern Programming IDEs.</p>
<p><b>Runtime errors or Exceptions</b> are erroneous situations in the runtime. The simplest example can be a division by Zero which results in a &#8220;Division by Zero&#8221; exception to be raised. These are different from Syntax errors in the sense that the compiler cannot detect these and hence the application compiles.</p>
<p><span style="text-align:center"><b>Click on the image to see the full screen version.</b></span></p>
<p><img src="/images/blog/csharp_tut_lesson_15_exception.png" width="500" height="297"/></p>
<p>In the above program, the application halts due to a DivideByZeroException. Since, the compiler cannot determine the number that will be entered by the user, the error goes undetected. At runtime, the statement <b>float Result = I / J;</b> raises the DivideByZero exception, if the user enters 0 as the input for the second variable.</p>
<p><b>Logical Errors</b> are those where the application compiles and runs properly but does not produce the required output, i.e errors in the logic of the program. They are harder to detect because they don&#8217;t throw any kind of exception. The best way to deal through them is to use the debugger, watches and call stacks.</p>
<h5>Exceptions</h5>
<p><b>System.Exception</b> is the base class for all other exceptions. Below this level are the <b>System.ApplicationException</b> and <strong>System.SystemException</strong> classes which are derived from the <b>System.Exception</b> class.</p>
<p><img src="/images/blog/csharp_tut_lesson_15_exception_hierarchy.png" /></p>
<p>The <i>SystemException</i> class acts as the base class for all the pre-defined Exceptions. <i>ApplicationException</i> class is to be used for any custom exceptions that you are to create in your application. Unlike the System Exceptions, these are forwarded by the application and not the CLR.</p>
<p>Below is a table listing some of the classes dervied from <i>SystemException</i> class.</p>
<table class="joomlaTable">
<tr>
<th>Exception Class</th>
<th>Description</th>
</tr>
<tr>
<td>System.IO.IOException</td>
<td>Handles Input/Output errors</td>
</tr>
<tr>
<td>System.IndexOutOfRangeException</td>
<td>Handles errors generated when a method refers to an array element, which is out of its bound.</td>
</tr>
<tr>
<td>System.NullReferenceException</td>
<td>Hanldes errors generated during the process of dereferencing a null object.</td>
</tr>
<tr>
<td>System.DivideByZeroException</td>
<td>Handles errors generated during the process of dividing a number by zero.</td>
</tr>
<tr>
<td>InvalidCastException</td>
<td>Handles errors generated during typecasting.</td>
</tr>
<tr>
<td>OutOfMemoryException</td>
<td>Handles memory allocation to the application errors.</td>
</tr>
</table>
<h5>Handling Exceptions</h5>
<p>Exceptions are handled by using exception handlers. These exception handlers divide the code in blocks.</p>
<p><b>The try Block</b></p>
<p>All the codes that have a chance of throwing exceptions are put inside the Try block. Given below is a simple try block code.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0600FF;">try</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">//Statements that may throw exceptions.</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p><b>The catch Block</b></p>
<p>If any statement inside the try block throws an exception, the execution control is passed onto the appropriate catch block. This allows the application to recover from exceptions. Catch block follows the following syntax:-</p>
<p>catch (&#8230;)<br />
{<br />
    //Error Handling Code<br />
}</p>
<p><i>Note: Every try block must have an associated catch block and vice versa.</i></p>
<p>The following code would trap the exception thrown in the previous example.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0600FF;">try</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">float</span> Result <span style="color: #008000;">=</span> I <span style="color: #008000;">/</span> J<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">catch</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;An error occured while trying to compute the result&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Whenever the user enters a value of 0 for J, an exception would be thrown. Since, this code is contained in a try block, the code inside the catch block will be executed and a message <b>An error occured while trying to compute the result</b> will be shown to the user.</p>
<p>In the above example, the type of exception being thrown is unknown. So, no matter what exception is thrown, the same message will be displayed.</p>
<p>You can specify the type of exception a catch block handles in the following way:-</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0600FF;">try</span>
<span style="color: #000000;">&#123;</span>
    Result <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>I <span style="color: #008000;">/</span> J<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>DivideByZeroException<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You tried to divide the number by zero&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The catch block declaration can also instantiate an object of the corresponding Exception class providing access to exception specific information &#8211; Error Codes, Description, etc.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0600FF;">try</span>
<span style="color: #000000;">&#123;</span>
    Result <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>I <span style="color: #008000;">/</span> J<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>DivideByZeroException ex<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>ex.<span style="color: #0000FF;">Message</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The code given below is a modified form of the earlier example.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="csharp">Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Enter Two Numbers:-&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">int</span> I <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">double</span> J <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToDouble</span><span style="color: #000000;">&#40;</span>Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">int</span> Result <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">try</span>
<span style="color: #000000;">&#123;</span>
    Result <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>I <span style="color: #008000;">/</span> J<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">catch</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;An error occured while trying to compute the result&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The result is {0}&quot;</span>, Result<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
Console.<span style="color: #0000FF;">Read</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>Line 8 can now generate two types of exception: <b>DivieByZeroException</b> and <b>OverflowException</b>. When the user enters a very high value, say 65536275 for the variable <b>I</b> and an extremely low value, say 0.0000001 for <b>J</b>. The result would exceed the range of the <b>int</b> datatype and the OverflowException would be thrown. Because the user would be treated with the same error message, he/she might not be able to determine the exact cause of the error.</p>
<p>This is where the catch block comes in handy. Multiple catch blocks can be attached to a try block. Each of them should differ in the type of exception they handle.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="csharp">Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Enter Two Numbers:-&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">int</span> I <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">double</span> J <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToDouble</span><span style="color: #000000;">&#40;</span>Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">int</span> Result <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">try</span>
<span style="color: #000000;">&#123;</span>
    Result <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>I <span style="color: #008000;">/</span> J<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>DivideByZeroException<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
&nbsp;
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You tried to divide the number by zero&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>OverflowException<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The operation resulted in an overflow&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">catch</span><span style="color: #000000;">&#40;</span>Exception<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;An error occured while trying to compute the result&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The result is {0}&quot;</span>, Result<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
Console.<span style="color: #0000FF;">Read</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>Now, if an OverflowException is thrown, the message <b>The operation resulted in an overflow</b> will be displayed. For the DivideByZero exception, the message <b>You tried to divide the number by zero</b> will be shown. For any other exception, the last message <b>An error occured while trying to compute the result</b> will be displayed.</p>
<p><b>Order of Catch Blocks</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">int</span> A <span style="color: #008000;">=</span> <span style="color: #FF0000;">5</span>, B <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">try</span>
<span style="color: #000000;">&#123;</span>
    A <span style="color: #008000;">=</span> A <span style="color: #008000;">/</span> B<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>Exception ex<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Exception&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>DivideByZeroException ex<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Divide By Zero Exception&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>The order of the catch block is very important.</p>
<blockquote><p>
A series of catch statements needs to be in decreasing order of derivation. For example, the most derived objects must appear first.
</p></blockquote>
<p>The above code generates the following compile-error: <b>A previous catch clause already catches all exceptions of this or of a super type (&#8216;System.Exception&#8217;).</b></p>
<p>If the catch(Exception) block is declared at the top, even a DivideByZeroException or the OverflowException will be handled by this block. This is because both of them are indirectly derived from the Exception class. Infact, C# does not allow such scenarios. So, you must first declare the exception class that is at a deeper level of the hierarchy.</p>
<p>The correct code would be as follows:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">int</span> A <span style="color: #008000;">=</span> <span style="color: #FF0000;">5</span>, B <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">try</span>
<span style="color: #000000;">&#123;</span>
    A <span style="color: #008000;">=</span> A <span style="color: #008000;">/</span> B<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>DivideByZeroException ex<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Divide By Zero Exception&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>Exception ex<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Exception&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p><b>The finally block</b><br />
This block is used to execute statements which are to be executed regardless of whether the exception is thrown or not. This may include a code such as to close a file, an existing SQL connection, etc. Only one finally block can exist for a try block. Also, the finally block is optional.</p>
<p>One may argue as to why we need the finally block because all statements below the entire try &#8211; catch block will be executed, irrespective of whether an exception is thrown or not. However, the code in the finally block is executed, even if a return statement is encountered inside the try or the catch block. The same is not true for the codes following the try &#8211; catch block.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">int</span> I <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span>, J <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #FF0000;">float</span> Result <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">try</span>
<span style="color: #000000;">&#123;</span>
    Result <span style="color: #008000;">=</span> I <span style="color: #008000;">/</span> J<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">catch</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;An error occured while trying to compute the result&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    return<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The result is {0}&quot;</span>, Result<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
Console.<span style="color: #0000FF;">Read</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>The output of the preceeding block of code would be:-</p>
<blockquote><p>An error occured while trying to compute the result</p></blockquote>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">int</span> I <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span>, J <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #FF0000;">float</span> Result <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">try</span>
<span style="color: #000000;">&#123;</span>
    Result <span style="color: #008000;">=</span> I <span style="color: #008000;">/</span> J<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">catch</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;An error occured while trying to compute the result&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    return<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">finally</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The result is {0}&quot;</span>, Result<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    Console.<span style="color: #0000FF;">Read</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>While, the output for this one would be:-</p>
<blockquote><p>
An error occured while trying to compute the result<br />
The result is 0
</p></blockquote>
<h5>Creating Custom Exceptions</h5>
<p>User defined exceptions can be created by deriving from the <b>System.ApplicationException</b> class or from any other system defined class. You can also derive Exceptions from these user-defined classes. The ultimate thing is that the new Exception class should be derived (directly or indirectly) from the Exception class.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">class</span> MyException <span style="color: #008000;">:</span> ApplicationException
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> MyException<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> Message<span style="color: #000000;">&#41;</span> <span style="color: #008000;">:</span> <span style="color: #0600FF;">base</span><span style="color: #000000;">&#40;</span>Message<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h5>Raising Exceptions</h5>
<p>Use the <i><strong>throw</strong></i> statement to raise your exceptions. This process requires the creation of a new object of the appropriate Exception class.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span><span style="color: #000000;">&#40;</span>MyException<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;My Exception was thrown&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Even the system defined exceptions can be thrown in this fashion.</p>
<p><i>Never create and throw an object of System.Exception class</i></p>
<div class="tutnav"></div>
]]></content:encoded>
			<wfw:commentRss>http://maxotek.net/blog/c-tutorial-lesson-15-error-handling-t54.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>C# Tutorial : Lesson 14 &#8211; File Handling</title>
		<link>http://maxotek.net/blog/csharp-tutorial-lesson-14-file-handling-t53.html</link>
		<comments>http://maxotek.net/blog/csharp-tutorial-lesson-14-file-handling-t53.html#comments</comments>
		<pubDate>Wed, 17 Oct 2007 13:19:56 +0000</pubDate>
		<dc:creator>partho</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://maxotek.net/blog/?p=53</guid>
		<description><![CDATA[Files &#038; Folders One of the ways of permanent storage of data is through files. A file is a collection of data stored on a secondary storage device, such as the Hard Disk. Every file has a name associated with it, such as Essay.txt. The name comprises of two parts the base name (in our [...]]]></description>
			<content:encoded><![CDATA[<div class="tutnav"></div>
<h5>Files &#038; Folders</h5>
<p>One of the ways of permanent storage of data is through files. A <span id="cFile" class="term">file</span> is a collection of data stored on a secondary storage device, such as the Hard Disk. Every file has a name associated with it, such as <b>Essay.txt</b>. The name comprises of two parts the <u>base name</u> (in our case &#8216;Essay&#8217;) and the <span id="cExtension"><u>extension</u></span> (txt). The portion before the period (.) is the base name whereas the one after it is the extension. A file name can also contain multiple periods &#8211; <b>Dr. No.avi</b>. The most significant period is always the last one. So, in this case, the base name of the file would be Dr. No and the extension avi.</p>
<p>The extension is what determines the type of the file. For example, a document has an extension of doc while a JPEG Image file has an extension of jpg. The base name is what we specify to identify that particular file.</p>
<p>Files are contained in folders or directories. A <span id="cDirectory" class="term">directory</span> itself can contain other files and folders, thus forming a hierarchy. Files within a folder (directory) need to have unique names. Files with same base name but different extensions are allowed. So, the file My File.txt and My File.doc can co-exist in a folder. The <span id="cFullPath">full path</span> of the file marks its complete address on a machine. For instance, if the file Notepad.exe is contained inside the Windows directory of your C drive, its path would be <b>&#8220;C:\Windows\Notepad.exe&#8221;</b>. Likewise, if it were to be contained inside the System32 directory which in turn is present in the Windows directory, the full path would be <b>&#8220;C:\Windows\System32\Notepad.exe&#8221;</b>.</p>
<p><i>Note: No two files on your computer can have the same full path.</i></p>
<h5 id="cStream">Stream</h5>
<p>A stream is a sequence of bytes travelling from a <u>source</u> to a <u>destination</u> over a communication medium. Streams can either be <u>input</u> or <u>output</u>. The input stream is used for reading while the output stream is used for writing.</p>
<p><i>Note: This stream concept does not just apply to files. It holds true for communication over a network through sockets too.</i></p>
<h5>File System Classes</h5>
<p>.NET provides a lot of <a href="?p=30#cClass">classes</a> for handling files. These are contained in the <b>System.IO</b> <a href="?p=13#cNamespace">namespace</a>. Listed below are various classes under this namespace.</p>
<table class="joomlaTable">
<tr>
<th>Class Name</th>
<th>Description</th>
</tr>
<tr>
<td>FileStream</td>
<td>Is used to read from and write to any location within a file.</td>
</tr>
<tr>
<td>BinaryReader</td>
<td>Is used to read primitive data types in the form of binary data from the stream.</td>
</tr>
<tr>
<td>StreamReader</td>
<td>Is used to read characters from a byte stream.</td>
</tr>
<tr>
<td>StringReader</td>
<td>Is used to read data from a string buffer.</td>
</tr>
<tr>
<td>BinaryWriter</td>
<td>Is used to write primitive data types in the form of binary data to the stream.</td>
</tr>
<tr>
<td>StreamWriter</td>
<td>Is used to write characters to a byte stream.</td>
</tr>
<tr>
<td>StringWriter</td>
<td>Is used to write data to a string buffer.</td>
</tr>
<tr>
<td>BinaryReader</td>
<td>Is used to read primitive data types in the form of binary data from the file stream.</td>
</tr>
<tr>
<td>StreamReader</td>
<td>Is used to read characters from the a byte stream.</td>
</tr>
<tr>
<td>DirectoryInfo</td>
<td>Is used to perform operations on directories.</td>
</tr>
<tr>
<td>FileInfo</td>
<td>Is used to perform operations on files.</td>
</tr>
</table>
<h5>FileStream Class</h5>
<p>The <strong>FileStream </strong>class resides under the <b>System.IO</b> namespace and is derived from the abstract class <em>Stream</em>. It supports random access through seeking. Before you begin reading from and writing to a file, an <a href="?p=30#cObject">object</a> of the <em>FileStream</em> class needs to initialized. The <a href="?p=39#cParameterizedConstructors">parameterized constructor</a> of this class allows to create/open files and set up appropriate file sharing modes.</p>
<p><u><b>Creating a new file.</b></u></p>

<div class="wp_syntax"><div class="code"><pre class="csharp">FileStream fs <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FileStream
    <span style="color: #000000;">&#40;</span>
        <span style="color: #666666;">&quot;TestFile.txt&quot;</span>,
        FileMode.<span style="color: #0000FF;">Create</span>,
        FileAccess.<span style="color: #0000FF;">Write</span>,
        FileShare.<span style="color: #0000FF;">Read</span>
    <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p><i>Note: The code is spanned across multiple lines for the sake of clarity.</i></p>
<p>The first <a href="?p=38#cParameter">parameter</a> to the constructor is the path to the file. In this case the new file will be created in the working directory of the application. A complete path such as <b>C:\Program Files\Maxotek\Tutorials\C-Sharp\Lesson14\TestFile.txt</b> can also be used. Backslash being the <a href="?p=13#cEscapeSequences">escape sequence</a> starter would need to be escaped in the string. The code would look something like:-</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">FileStream fs <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FileStream
    <span style="color: #000000;">&#40;</span>
        <span style="color: #666666;">&quot;C:<span style="color: #008080; font-weight: bold;">\\</span>Program Files<span style="color: #008080; font-weight: bold;">\\</span>Maxotek<span style="color: #008080; font-weight: bold;">\\</span>Tutorials<span style="color: #008080; font-weight: bold;">\\</span>C-Sharp<span style="color: #008080; font-weight: bold;">\\</span>Lesson14<span style="color: #008080; font-weight: bold;">\\</span>TestFile.txt&quot;</span>,
        FileMode.<span style="color: #0000FF;">Create</span>,
        FileAccess.<span style="color: #0000FF;">Write</span>,
        FileShare.<span style="color: #0000FF;">Read</span>
    <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Another way of doing this, is to use the @ character before the string. This prevents any escape sequence character as the backslash itself is taken as a normal character.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">FileStream fs <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FileStream
    <span style="color: #000000;">&#40;</span>
        <span style="color: #666666;">@&quot;C:\Program Files\Maxotek\Tutorials\C-Sharp\Lesson14\TestFile.txt&quot;</span>,
        FileMode.<span style="color: #0000FF;">Create</span>,
        FileAccess.<span style="color: #0000FF;">Write</span>,
        FileShare.<span style="color: #0000FF;">Read</span>
    <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>The second parameter to the constructor is the <em>FileMode</em> <a href="?p=36#cEnumeration">enumeration</a>. It can have any of the following values.</p>
<table class="joomlaTable">
<tr>
<th>File Mode</th>
<th>Description</th>
</tr>
<tr>
<td>Create</td>
<td>Creates a new file or truncates the existing file.</td>
</tr>
<tr>
<td>CreateNew</td>
<td>Creates a new file. If the file already exists, throws a <b>System.IO.IOException</b>.</td>
</tr>
<tr>
<td>Open</td>
<td>Opens an existing file. Throws a <b>System.IO.FileNotFoundException</b> if the file does not exist.</td>
</tr>
<tr>
<td>OpenOrCreate</td>
<td>Opens an existing file or creates a new one. The difference between this mode and the Create mode is that it does not truncate the file.</td>
</tr>
<tr>
<td>Append</td>
<td>Opens the file and seeks to the end. A new file is created if the file does not exist.</td>
</tr>
<tr>
<td>Truncate</td>
<td>Opens an existing file and truncates its content so that the file size becomes zero. Attempting to read in this mode throws an exception.</td>
</tr>
</table>
<p>The third parameter is the <em>FileAccess </em>which specifies whether the file is to be opened for Reading (<em>FileAccess.Read</em>), Writing (<em>FileAccess.Write</em>) or both (<em>FileAccess.ReadWrite</em>).</p>
<p>The last parameter is FileShare mode which states how the file will be shared.</p>
<table class="joomlaTable">
<tr>
<th>FileShare Mode</th>
<th>Description</th>
</tr>
<tr>
<td>Read</td>
<td>Allows other handles to read from the file.</td>
</tr>
<tr>
<td>Write</td>
<td>Allows other handles to write to the file.</td>
</tr>
<tr>
<td>Delete</td>
<td>Allows subsequent deleting of the file.</td>
</tr>
<tr>
<td>Inheritable</td>
<td>Makes the file handle inheritable to child processes.</td>
</tr>
<tr>
<td>None</td>
<td>Declines sharing of file. No other process can open the file until it is closed.</td>
</tr>
</table>
<p><i>Note: The constructor is <a href="?p=43#cFunctionOverloading">overloaded</a> into many other forms which take various other types and combinations of parameters. The above form was one of the basic ones.</i></p>
<p><u><b>Writing to the File</b></u></p>
<p>We use the <b>StreamWriter</b> class which is <a href="?p=47#cInheritance">inherited</a> from the abstract class <b>TextWriter</b> to write a series of characters. After opening the file in the appropriate mode (<em>Write </em>or <em>ReadWrite </em>in this case), a new object of the <em>StreamWriter</em> class is created. The object of the <em>FileStream </em>class is passed to it, thus associating the stream with the file. After this, the content can be written to the file by using the <b>Write</b> or the <b>WriteLine</b> <a href="?p=38">method</a>. <em>WriteLine </em>appends an end of line to the content. These two methods are highly overloaded to enable almost all built in data types to be directly written.</p>
<p>Once you have done all the writing, make sure you close the file using the <b>Close</b> method. This ensures all the content is physically written to the file. For performance reasons, the write operation is buffered and sometimes the content might not be physically written to the file even after the <em>Write </em>method was called. To force all the buffers to be cleared and all buffered content to be written to the underlying stream (File in our case), use the <b>Flush</b> method.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="csharp">FileStream fs <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FileStream
    <span style="color: #000000;">&#40;</span>
        <span style="color: #666666;">&quot;TestFile.txt&quot;</span>,
        FileMode.<span style="color: #0000FF;">Create</span>,
        FileAccess.<span style="color: #0000FF;">Write</span>,
        FileShare.<span style="color: #0000FF;">Read</span>
    <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
StreamWriter sw <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StreamWriter<span style="color: #000000;">&#40;</span>fs<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
sw.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Hello World&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
sw.<span style="color: #0000FF;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>     <span style="color: #008080; font-style: italic;">// Close the Stream</span>
fs.<span style="color: #0000FF;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>     <span style="color: #008080; font-style: italic;">// Close the File</span></pre></td></tr></table></div>

<p><u><b>Reading from a fie</b></u></p>
<p>The <b>StreamReader</b> class is used to read a series of characters from a <em>FilStream</em>. This class is derived from the abstract class <em>TextReader</em>. Before reading, the file must be opened in the appropriate mode (Read or ReadWrite). To Read the next character or the next set of characters, use the <b>Read</b> method. This method has two forms. One that does not take any parameters and reads the next character. It returns the byte value of the character. The other one takes three parameters:-</p>
<ul>
<li>An array of characters &#8211; The read characters are stored in the variable passed here.</li>
<li>The index of the buffer at which to begin writing</li>
<li>Maximum number of characters to read</li>
</ul>
<p>The <b>ReadLine</b> method reads a line of characters and returns the result in the form of a string.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="csharp">FileStream fs <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FileStream
    <span style="color: #000000;">&#40;</span>
        <span style="color: #666666;">&quot;TestFile.txt&quot;</span>,
        FileMode.<span style="color: #0000FF;">Open</span>,
        FileAccess.<span style="color: #0000FF;">Read</span>,
        FileShare.<span style="color: #0000FF;">Read</span>
    <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
StreamReader sr <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StreamReader<span style="color: #000000;">&#40;</span>fs<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">string</span> str <span style="color: #008000;">=</span> sr.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">while</span> <span style="color: #000000;">&#40;</span>str <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>str<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    str <span style="color: #008000;">=</span> sr.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
sr.<span style="color: #0000FF;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>     <span style="color: #008080; font-style: italic;">// Close the Stream</span>
fs.<span style="color: #0000FF;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>     <span style="color: #008080; font-style: italic;">// Close the File</span></pre></td></tr></table></div>

<p>The file pointer can be seeked to any position of the file using the <em>BaseStream</em> property&#8217;s <b>Seek</b> method. This method takes two parameters. The first, a byte offset relative to the Origin (second) parameter. This value can be either positive which moves the pointer down the file or negative which moves the file pointer upwards. The second parameter known as the <b>Origin</b> parameter indicates the reference point to obtain the new position. The permissible values are Begin, Current and End.</p>
<p>The following line of code moves the file pointer to the 5th character from the beginning.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">sr.<span style="color: #0000FF;">BaseStream</span>.<span style="color: #0000FF;">Seek</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">5</span>, SeekOrigin.<span style="color: #0000FF;">Begin</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Moves the pointer to the start.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">sr.<span style="color: #0000FF;">BaseStream</span>.<span style="color: #0000FF;">Seek</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span>, SeekOrigin.<span style="color: #0000FF;">Begin</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Moves the pointer to 5 characters ahead of the current position.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">sr.<span style="color: #0000FF;">BaseStream</span>.<span style="color: #0000FF;">Seek</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">5</span>, SeekOrigin.<span style="color: #0000FF;">Current</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Moves the pointer 5 characters backward from the current position.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">sr.<span style="color: #0000FF;">BaseStream</span>.<span style="color: #0000FF;">Seek</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">-5</span>, SeekOrigin.<span style="color: #0000FF;">Begin</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Moves the pointer to the end.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">sr.<span style="color: #0000FF;">BaseStream</span>.<span style="color: #0000FF;">Seek</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span>, SeekOrigin.<span style="color: #0000FF;">End</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>The <b>Peek</b> method is used to read the next character without consuming it, i.e the file pointer does not move ahead.</p>
<h5>Implementing Binary Read &#038; Write</h5>
<p>The <i>StreamReader</i> and <i>StreamWriter</i> classes work with character data. In this mode everything is written as plain text. To implement binary operations, wherein a number such as 327.68 would be written as a float value consuming four bytes and not just as plain text, we need to use the <b>BinaryReader</b> and <b>BinaryWriter</b> classes.</p>
<p>They are very similar to their text counterparts except that no Line (<em>ReadLine</em> and <em>WriteLine</em>) methods are provided. The <em>BinaryReader</em> class also supports data type specific methods such as <em>ReadInt32</em>, <em>ReadDouble</em>, etc. These allow you to directly read the content from the file in the appropriate format. If we were to use the <em>StreamReader</em> class, we would have to convert the string to integer or double format using the <em>Convert.ToInt32</em> and <em>Convert.ToDouble</em> methods.</p>
<p><b><u>Writing to File</u></b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">int</span> MyNumber <span style="color: #008000;">=</span> <span style="color: #FF0000;">69</span><span style="color: #008000;">;</span>
BinaryWriter bw <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BinaryWriter<span style="color: #000000;">&#40;</span>fs<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
bw.<span style="color: #0000FF;">Write</span><span style="color: #000000;">&#40;</span>MyNumber<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p><b><u>Reading from file</u></b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="csharp">BinaryReader br <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BinaryReader<span style="color: #000000;">&#40;</span>fs<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #FF0000;">int</span> MyNumber <span style="color: #008000;">=</span> br.<span style="color: #0000FF;">ReadInt32</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<h5>Implementing the Windows File System</h5>
<p>Often we need to browse directories and locate files. Many such operations can be accomplished by using the two classes &#8211; <b>DirectoryInfo</b> and <b>FileInfo</b>. Both of these are derived from the <b>FileSystemInfo</b> class.</p>
<p>The tables below list some of the commonly used properties and methods corresponding to both of these classes.</p>
<p><u><b>Properties of DirectoryInfo Class</b></u></p>
<table class="joomlaTable">
<tr>
<th>Property</th>
<th>Description</th>
</tr>
<tr>
<td>Attributes</td>
<td>Gets or sets attributes associated with the current directory.</td>
</tr>
<tr>
<td>CreationTime</td>
<td>Gets or sets the Creation time of the directory.</td>
</tr>
<tr>
<td>Exists</td>
<td>Gets a Boolean value indicating whether the directory exists </td>
</tr>
<tr>
<td>FullName</td>
<td>Gets a string containing the full path of the directory.</td>
</tr>
<tr>
<td>LastAccessTime</td>
<td>Gets the last accessed time of the directory.</td>
</tr>
<tr>
<td>Name</td>
<td>Gets a string containing the name of the directory.</td>
</tr>
</table>
<p><b><u>Methods of DirectoryInfo Class</u></b></p>
<table class="joomlaTable">
<tr>
<th>Method</th>
<th>Description</th>
</tr>
<tr>
<td>Create</td>
<td>Creates a directory.</td>
</tr>
<tr>
<td>Delete</td>
<td>Deletes a directory.</td>
</tr>
<tr>
<td>GetDirectories</td>
<td>Returns the directories in the current directory. Supports filtering and recursive listing.</td>
</tr>
<tr>
<td>GetFiles</td>
<td>Returns the file in the current directory.</td>
</tr>
</table>
<p><b><u>Properties of FileInfo class</u></b></p>
<table class="joomlaTable">
<tr>
<th>Property</th>
<th>Description</th>
</tr>
<tr>
<td>Attributes</td>
<td>Gets or sets the attributes associated with the current file.</td>
</tr>
<tr>
<td>CreationTime</td>
<td>Gets or sets the CreationTime of the file.</td>
</tr>
<tr>
<td>Directory</td>
<td>Gets an instance of the directory to which the file belongs to.</td>
</tr>
<tr>
<td>Exists</td>
<td>Gets a Boolean value indicating whether the file exists.</td>
</tr>
<tr>
<td>Extension</td>
<td>Gets a string containing the extension of the file.</td>
</tr>
<tr>
<td>FullName</td>
<td>Gets a string containing the full path to the file.</td>
</tr>
<tr>
<td>LastAccessTime</td>
<td>Gets the last access time of the file.</td>
</tr>
<tr>
<td>LastWriteTime</td>
<td>Gets the time of the last wriiten activity on the file.</td>
</tr>
<tr>
<td>Length</td>
<td>Gets the length of the file in Bytes.</td>
</tr>
<tr>
<td>Name</td>
<td>Gets the name of the File.</td>
</tr>
</table>
<p><b><u>Methods of FileInfo class</u></b></p>
<table class="joomlaTable">
<tr>
<th>Method</th>
<th>Description</th>
</tr>
<tr>
<td>Create</td>
<td>Creates a new file.</td>
</tr>
<tr>
<td>AppendText</td>
<td>Appends a text to the file.</td>
</tr>
<tr>
<td>Delete</td>
<td>Deletes the file.</td>
</tr>
<tr>
<td>Open</td>
<td>Opens the file.</td>
</tr>
<tr>
<td>OpenRead</td>
<td>Opens a file in the read-only mode.</td>
</tr>
</table>
<h5>Creating Objects</h5>
<p>Creating a <i>DirectoryInfo</i> or <em>FileInfo</em> object is very simple. The constructor takes the path to the file.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">DirectoryInfo di <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DirectoryInfo<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;C:<span style="color: #008080; font-weight: bold;">\\</span>Windows&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
FileInfo fi <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FileInfo<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;C:<span style="color: #008080; font-weight: bold;">\\</span>Windows<span style="color: #008080; font-weight: bold;">\\</span>Notepad.exe&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h5>Listing All Files in a Directory</h5>
<p>The following code snippet lists all the files in the C:\Windows directory.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="csharp">DirectoryInfo di <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DirectoryInfo<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;C:<span style="color: #008080; font-weight: bold;">\\</span>Windows&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
FileInfo<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> fis <span style="color: #008000;">=</span> di.<span style="color: #0000FF;">GetFiles</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>FileInfo fi <span style="color: #0600FF;">in</span> fis<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>fi.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<div class="tutnav"></div>
]]></content:encoded>
			<wfw:commentRss>http://maxotek.net/blog/csharp-tutorial-lesson-14-file-handling-t53.html/feed</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>C# Tutorial : Lesson 13 &#8211; Inheritance &#8211; Part II</title>
		<link>http://maxotek.net/blog/csharp-tutorial-lesson-12-inheritance-part-ii-t52.html</link>
		<comments>http://maxotek.net/blog/csharp-tutorial-lesson-12-inheritance-part-ii-t52.html#comments</comments>
		<pubDate>Sun, 14 Oct 2007 01:22:56 +0000</pubDate>
		<dc:creator>partho</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://maxotek.net/blog/?p=52</guid>
		<description><![CDATA[Abstract Class Consider the term Vehicle. It does not have an existence of its own. However, types of vehicles; namely, Car, Aeroplane, Bus, etc do. Similarly, we can have Abstract classes which cannot be instantiated thus exhibiting the abstract behavior. They merely contain the skeleton of the class but not its implementation. The abstract keyword [...]]]></description>
			<content:encoded><![CDATA[<div class="tutnav"></div>
<h5>Abstract Class</h5>
<p>Consider the term Vehicle. It does not have an existence of its own. However, types of vehicles; namely, Car, Aeroplane, Bus, etc do. Similarly, we can have Abstract classes which cannot be instantiated thus exhibiting the abstract behavior. They merely contain the skeleton of the class but not its implementation. The abstract <b>keyword</b> is used to declare such a class.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="csharp">abstract <span style="color: #FF0000;">class</span> Vehicle
<span style="color: #000000;">&#123;</span>
&nbsp;
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// Abstract Class cannot be instantiated</span>
    Vehicle obj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Vehicle<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>    <span style="color: #008080; font-style: italic;">// Shows Compilation Error.</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h5>Abstract Methods</h5>
<p>Abstract methods contain the function signature and return type, but no body. A child class can override the abstract method thus providing its implementation. Abstract methods are also declared by using the <b>abstract</b> keyword.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="csharp">abstract <span style="color: #FF0000;">class</span> Vehicle
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> abstract <span style="color: #0600FF;">void</span> Run<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Car <span style="color: #008000;">:</span> Vehicle
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> Run<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Run the Car&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Bus <span style="color: #008000;">:</span> Vehicle
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> Run<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Run the Bus&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>In this example, the abstract method Run() is declared in the Vehicle class. Notice the lack of the { } braces which marks the lack of a body. Since the Vehicle class cannot be instantiated, it does not need to have an implementation for the Run() method. The actual implementation is contained in its derived classes &#8211; Car, Bus. Thus, the abstract class only forms the skeleton of the child classes which exhibit specialization by overriding and implementing the abstract methods.</p>
<p><i>Note: Abstract methods can only be defined inside an abstract class.</i></p>
<h5>Overriding Methods</h5>
<p>In the previous example the <b>override</b> keyword is used. A parent class method can be overridden by a child class. In this way it provides its own implementation shadowing the one of the base class. A method must be declared as <b>abstract</b> or <b>virtual</b> to be overridden inside the child class.</p>
<h5>Virtual Functions</h5>
<p>The difference between a virtual function/method and an abstract method is that while the latter does not provide an implementation, the former does. If a virtual function of the parent class is not overridden, the method is inherited as it is, inside the child class. Again, we use the <b>virtual</b> keyword for declaring virtual functions.</p>
<p>The following example shows various cases when a method can/cannot be overridden.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
</pre></td><td class="code"><pre class="csharp">abstract <span style="color: #FF0000;">class</span> Vehicle
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// Abstract Method. Contains no body.</span>
    <span style="color: #0600FF;">public</span> abstract <span style="color: #0600FF;">void</span> Run<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Car <span style="color: #008000;">:</span> Vehicle
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// Abstract method is overridden.</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> Run<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Run the Car&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Normal Method. Cannot be overridden.</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Brake<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Stop the Car&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Virtual Method. Can be overridden.</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">virtual</span> <span style="color: #0600FF;">void</span> Accelerate<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Step on the gas&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">class</span> BMW <span style="color: #008000;">:</span> Car
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// An overridden method can be further overridden.</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> Run<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Run the BMW&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Shows Compilation Error.</span>
    <span style="color: #008080; font-style: italic;">// The Brake method of Car is</span>
    <span style="color: #008080; font-style: italic;">// not declared as virtual or abstract.</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> Brake<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Stop the Car&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// Virtual method is overridden.</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> Accelerate<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Step on the gas&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>From the following you can deduce that for a method to be overridden, it must be declared as <b>abstract</b> or <b>virtual</b>. An overridden method can be further overridden because it carries over the virtual modifier.</p>
<h5>Sealed Classes</h5>
<p>So many ways to modify a class but none to protect? Fear not, <b>sealed</b> classes are here to the rescue. This modifier prevents a class from being tampered by not allowing other classes to inherit from it.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">sealed</span> <span style="color: #FF0000;">class</span> Ferari
<span style="color: #000000;">&#123;</span>
&nbsp;
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// Shows Error. Cannot inherit from sealed class.</span>
<span style="color: #FF0000;">class</span> McLaren <span style="color: #008000;">:</span> Ferari
<span style="color: #000000;">&#123;</span>
&nbsp;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h5>Sealed Methods</h5>
<p>Use the sealed modifier to prevent a method from being overridden. Normally, you do not need to use this modifier as the methods are not overridable by default. However, if you want to protect an overridden method from being further overridden, you should use the sealed method instead of sealing off the entire class.</p>
<h5>Interfaces</h5>
<p>Remember that C# does not support multiple inheritance? Multiple inheritance tends to cause more problems than it solves. However, the ability to derive methods and properties from multiple sources is present in C#. This is done using Interfaces. Interfaces only contain the declaration part of a class. The actual definition which comprises of the body of the method is present inside the class which implements the interface.</p>
<h5>Declaring Interfaces</h5>
<p>They are declared similar to how classes are. Only differences are that they can only contain methods and properties (no variables), they do not contain the definition for these methods/properties and off-course the interface keyword.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #FF0000;">interface</span> Flyer
<span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Fly<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h5>Implementing Interfaces</h5>
<p>Classes do not inherit from interfaces, rather implement them. Although, the process of doing this is the same.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #FF0000;">class</span> Aeroplane <span style="color: #008000;">:</span> Flyer
<span style="color: #000000;">&#123;</span>
&nbsp;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Multiple interfaces can be implemented as follows:-</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #FF0000;">class</span> Aeroplane <span style="color: #008000;">:</span> Flyer, Vehicle
<span style="color: #000000;">&#123;</span>
&nbsp;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p><i>Here, Vehicle is also assumed to be an interface.</i></p>
<p>A class can inherit from another class and implement an interface in a similar fashion:-</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #FF0000;">class</span> Bird <span style="color: #008000;">:</span> Mammal, Flyer
<span style="color: #000000;">&#123;</span>
&nbsp;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p><i>Note: Mammal is a class here.</i></p>
<h5>Inheriting Interfaces</h5>
<p>Interfaces themselves can inherit from other interfaces. Again, the process is the same.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #FF0000;">interface</span> MechanicalFlyer <span style="color: #008000;">:</span> Flyer
<span style="color: #000000;">&#123;</span>
&nbsp;
<span style="color: #000000;">&#125;</span></pre></div></div>

<h5>Why use interfaces?</h5>
<p>Interfaces provide the skeletal structure of the classes which implement them. They separate the definition of objects from their implementation.</p>
<h5>Why not just use Abstract classes?</h5>
<p>Abstract classes are meant to be used when you want only some of the methods/properties to be implemented by the sub class. Besides, a class cannot inherit from multiple classes but it can implement multiple interfaces.</p>
<p>The following example depicts the need for interfaces.</p>
<p><img src="/images/blog/csharp_tut_lesson_13_interfaces.png" /></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code"><pre class="csharp">abstract <span style="color: #FF0000;">class</span> Animal
<span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Eat<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
	<span style="color: #000000;">&#123;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
abstract <span style="color: #FF0000;">class</span> Vehicle
<span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Run<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
	<span style="color: #000000;">&#123;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">interface</span> Flyer
<span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Fly<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Aeroplane <span style="color: #008000;">:</span> Vehicle, Flyer
<span style="color: #000000;">&#123;</span>
&nbsp;
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Bird <span style="color: #008000;">:</span> Animal, Flyer
<span style="color: #000000;">&#123;</span>
&nbsp;
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>As you can see, the two sub classes Bird and Aeroplane derive from the Animal and Vehicle classes respectively. Both have the characteristics of their respective base classes. The Bird like any other animal, eats while the Aeroplane being a vehicle, runs. However, they both share a common trait &#8211; the ability to fly. This ability is neither possessed by all animals nor by all vehicles. So it cannot be defined in either of the base classes. Again, it is not only possessed by the Aeroplane and Bird, some insects, baloons and other types of vehicles such as the Helicopter also possess it. It wouldn&#8217;t be effective to define this ability in each of them. Actually, it will be defined individually in each of these classes because each have their own way of flying, the bird flaps the wings, whereas the helicopter roatates its through a mechanical engine. However, this ability is declared in the Flyer interface so that any class which implements this interface would have to define the Fly() method by overriding it.</p>
<div class="tutnav"></div>
]]></content:encoded>
			<wfw:commentRss>http://maxotek.net/blog/csharp-tutorial-lesson-12-inheritance-part-ii-t52.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>C# Tutorial : Lesson 12 &#8211; Inheritance &#8211; Part I</title>
		<link>http://maxotek.net/blog/csharp-tutorial-lesson-12-inheritance-t47.html</link>
		<comments>http://maxotek.net/blog/csharp-tutorial-lesson-12-inheritance-t47.html#comments</comments>
		<pubDate>Fri, 24 Aug 2007 11:04:15 +0000</pubDate>
		<dc:creator>partho</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://maxotek.net/blog/?p=47</guid>
		<description><![CDATA[One of the important aspects of the Object Oriented Methodology is relationship. Objects do not exist as isolated entities, rather, they exhibit some kind of relationship with other objects. Some of the common relationships between the classes are listed below:- Instantiation Relationship This is the relationship that exists between a class and its instance or [...]]]></description>
			<content:encoded><![CDATA[<div class="tutnav"></div>
<p>One of the important aspects of the <a href="?p=30#cOOP">Object Oriented Methodology</a> is relationship. <a href="?p=30#cObject">Objects</a> do not exist as isolated entities, rather, they exhibit some kind of relationship with other objects. Some of the common relationships between the classes are listed below:-</p>
<h5>Instantiation Relationship</h5>
<p>This is the relationship that exists between a <a href="?p=30#cClass">class</a> and its instance or object. Real world examples of such a relationship can be:-</p>
<ul>
<li>A Ferari is a Car</li>
<li>A Mobile Phone is a type of electronic device</li>
</ul>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">class</span> Car
<span style="color: #000000;">&#123;</span>
	<span style="color: #FF0000;">string</span> Model<span style="color: #008000;">;</span>
	<span style="color: #FF0000;">string</span> Company<span style="color: #008000;">;</span>
	<span style="color: #FF0000;">string</span> SerialNumber<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	Car MyCar <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>	<span style="color: #008080; font-style: italic;">// Instantiation Relationship between MyCar &amp; Car</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h5>Composition Relationship</h5>
<p>Classes can be nested i.e a Class can contain another class. The relationship between two such classes is called composition relationship.</p>
<p><img src="/images/blog/csharp_tut_lesson_12_composition.png" alt="Composition" /></p>
<p>The following code represents the Composition relationship that is depicted in the above diagram.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">class</span> Car
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">string</span> SerialNumber<span style="color: #008000;">;</span>
    <span style="color: #FF0000;">string</span> Model<span style="color: #008000;">;</span>
    <span style="color: #FF0000;">string</span> Color<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #FF0000;">class</span> Engine
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">string</span> Type<span style="color: #008000;">;</span>
        <span style="color: #FF0000;">string</span> Model<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #FF0000;">class</span> Wheel
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">int</span> Width<span style="color: #008000;">;</span>
        <span style="color: #FF0000;">string</span> Manufacturer<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h5>Utilization Relationship</h5>
<p>The concept of OOP allows a class to make use of another class i.e delegate some portion of its work to another specialized class. The relationship between these two classes is termed as utilization. Ferari an object of the car class, is driven by Michael, an object of the driver class. These two entities have a utilization relationship between them.</p>
<p>The following code snippet demonstrates the utilization relationship between the <b>Sorter</b> and the <b>Swapper</b> class.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">class</span> Sorter
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Sort<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> A<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> I <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> I <span style="color: #008000;">&lt;</span> A.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">-</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span> I<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> J <span style="color: #008000;">=</span> I <span style="color: #008000;">+</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span> J <span style="color: #008000;">&lt;</span> A.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span> J<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>A<span style="color: #000000;">&#91;</span>I<span style="color: #000000;">&#93;</span> <span style="color: #008000;">&gt;</span> A<span style="color: #000000;">&#91;</span>J<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    <span style="color: #008080; font-style: italic;">// Utilizes the Swapper Class to do the swapping</span>
                    Swapper.<span style="color: #0000FF;">Swap</span><span style="color: #000000;">&#40;</span>A<span style="color: #000000;">&#91;</span>I<span style="color: #000000;">&#93;</span>, A<span style="color: #000000;">&#91;</span>J<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Swapper
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Swap<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">int</span> Num1, <span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">int</span> Num2<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">int</span> Temp <span style="color: #008000;">=</span> Num1<span style="color: #008000;">;</span>
        Num1 <span style="color: #008000;">=</span> Num2<span style="color: #008000;">;</span>
        Num2 <span style="color: #008000;">=</span> Temp<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>This example uses the bubble sort algorithm to sort an array of integers in the ascending order. While sorting, two elements of the list need to be swapped when they are not arranged ascendingly. The Sorter class employs the Swapper class for this job thus utilizing it.</li>
<h5 id="cInheritance">Inheritance</h5>
<p>Just as a child inherits qualities from his/her parents, a class can inherit data members and functions from another class. Consider the following class diagram:-</p>
<p><img src="/images/blog/csharp_tut_lesson_12_inheritance.png" title="Inheritance" /></p>
<p>The Mammals class is the base class as it inherits its attributes to other classes. Dogs, cats &#038; Humans are its child classes. This hierarchy is derived from the common set of attributes that the classes share. Mammals, for example are warm blooded, vertebrates, possess external ears and have hair on their body. These characteristics also pertain to Dogs, Cats, Humans, Lions, Tigers and Leopards, thus making them mammals. In C#, a class can have multiple child classes but only 1 base class. Multiple inheritance which existed in languages such as C++ has been scrapped because they tend to cause more problems than they solve.</p>
<p>Some key terms related to Inheritance are listed below.</p>
<ul>
<li><b>Base(Super) Class</b> &#8211; The class that inherits its properties to other classes.</li>
<li><b>Child(Sub) Class</b> &#8211; The class that inherits its properties from other classes.</li>
<li><b>Multi-level Inheritance</b> &#8211; A class which inherits from another class, serves as the base class for a third class. In the preeceding diagram, Lions, Tigers &#038; Leopards are derived from the Cats class which itself is derived from the Mammals class. This is called multi-level inheritance.</li>
<li><b>Generalization</b> &#8211; Classes that inherit from the same base class have certain common attributes which have been inherited from the common base class. This relationship is called Generalization.</li>
<li><b>Specialization</b> &#8211; It refers to the uncommon characteristics of a sub class, those that make it different from others. When we say that Human is a kind of Mammal, we imply that they have the common properties of Mammals along with some specialized characteristics that make them different from other Mammals &#8211; They walk on two legs. Specialization is the opposite of Generalization.</li>
</ul>
<h5>Implementing Inheritance</h5>
<p><br/></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">namespace</span> ConsoleApplication1
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Cars MyFerari <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Cars<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            MyFerari.<span style="color: #0000FF;">NumberOfWheels</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">4</span><span style="color: #008000;">;</span>
            MyFerari.<span style="color: #0000FF;">Drive</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Vehicles
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> Name<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> NumberOfWheels<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Drive<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Cars <span style="color: #008000;">:</span> Vehicles
    <span style="color: #000000;">&#123;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>In this example, the Cars class is a sub class which is derived from the Vehicles class. The Cars class inherits the data member NumberOfWheels and the member function &#8211; Drive() from the Vehicles class. So, the MyFerari object of the Car class has access to these members.</p>
<p><i>Note: Private members are not accessible from the sub class. So, the follwoing code would cause a <b>&#8216;ConsoleApplication1.Vehicles.Name&#8217; is inaccessible due to its protection level.</b> error.</i></p>

<div class="wp_syntax"><div class="code"><pre class="csharp">MyFerari.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Ferari&quot;</span><span style="color: #008000;">;</span></pre></div></div>

<h5>Determining Inheritance Hierarchies</h5>
<p>This process is very simple as the only thing one needs to remember is that the sub class should be a type of the base class. For example: Human is a type of Mammal, Car is a type of vehicle and so on.</p>
<p><i>Note: Improper usage of Inheritance will not result in any syntactical error. But, the design model for the program would be at fault.</i></p>
<h5>Constructor Inovking Order</h5>
<p><a href="?p=39#cConstructor">Constructors</a> being unique to a class are not inherited. Whenever an object of a child class is created, the constructor of both the parent and the child class is invoked. The parent class must come into existence before its child class can. Therefore, the constructor of the base class is invoked first followed by the constructor of the derived class. The destructors are invoked in the opposite order &#8211; derived to base. This is because the child class must be destroyed before the parent class.</p>
<p>The following program confirms these two order.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> ConsoleApplication1
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Cars MyFerari <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Cars<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Vehicles
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> Vehicles<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Vehicles -&gt; Constructor Invoked&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        ~Vehicles<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Vehicles -&gt; Destructor Invoked&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Cars <span style="color: #008000;">:</span> Vehicles
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> Cars<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Cars -&gt; Constructor Invoked&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        ~Cars<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Cars -&gt; Destructor Invoked&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<div class="tutnav"></div>
]]></content:encoded>
			<wfw:commentRss>http://maxotek.net/blog/csharp-tutorial-lesson-12-inheritance-t47.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>C# Tutorial : Lesson 11 &#8211; Polymorphism &#8211; Part II</title>
		<link>http://maxotek.net/blog/csharp-tutorial-lesson-11-polymorphism-part-ii-t44.html</link>
		<comments>http://maxotek.net/blog/csharp-tutorial-lesson-11-polymorphism-part-ii-t44.html#comments</comments>
		<pubDate>Sat, 11 Aug 2007 09:46:15 +0000</pubDate>
		<dc:creator>partho</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://maxotek.net/blog/?p=44</guid>
		<description><![CDATA[Operator Overloading By default, out of the various C# operators, only the dot operator can be applied to user-defined types. Consider the following code snippet:- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Program &#123; static void Main&#40;string&#91;&#93; args&#41; &#123; Car Car1 = new Car&#40;&#41;; Car [...]]]></description>
			<content:encoded><![CDATA[<div class="tutnav"></div>
<h5>Operator Overloading</h5>
<p>By default, out of the various C# operators, only the dot operator can be applied to user-defined types. Consider the following code snippet:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">class</span> Program
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Car Car1 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Car Car2 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        Car Car3 <span style="color: #008000;">=</span> Car1 <span style="color: #008000;">+</span> Car2<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Car
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Speed<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>The compiler generates an error at line 8 saying that the operator + cannot be applied to objects of the <b>Car</b> class. How is the compiler supposed to know whether we want to add the speeds of two cars or concatenate their names. This is where the concept of Operator Overloading jumps in. Before we see how the + operator is prepared to work with the objects of the <b>Car</b> class, we need to understand how the concept works. Given below is a code snippet which accomplishes the addition in objects using a specialized method &#8211; <b>Add()</b>.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Program
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Car Car1 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Car Car2 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Car1.<span style="color: #0000FF;">Speed</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">30</span><span style="color: #008000;">;</span>
        Car2.<span style="color: #0000FF;">Speed</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">70</span><span style="color: #008000;">;</span>
&nbsp;
        Car Car3 <span style="color: #008000;">=</span> Car.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>Car1, Car2<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Car3's Speed = {0}&quot;</span>, Car3.<span style="color: #0000FF;">Speed</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">Read</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Car
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Speed<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> Car Add<span style="color: #000000;">&#40;</span>Car Car1, Car Car2<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Car NewCar <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        NewCar.<span style="color: #0000FF;">Speed</span> <span style="color: #008000;">=</span> Car1.<span style="color: #0000FF;">Speed</span> <span style="color: #008000;">+</span> Car2.<span style="color: #0000FF;">Speed</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">return</span> NewCar<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>The <b>Add</b> method is declared as static so it can be invoked at the class level as <b>Car.Add()</b>. It takes two parameters of the type <b>Car</b> as inputs. It then creates a new object of the Car class, with a speed equal to the sum of the speeds of the input objects &#8211; <b>Car1</b> and <b>Car2</b>. Finally, the new object is returned. In this way, the addition of two objects can be accomplished. The same concept is used in Operator Overloading, except for the fact that the specialized function in their case are of the format <b>operator &lt;operator name&gt;</b>.</p>
<p><i>Note: The logic inside the Add function is totally up to the the programmer.</i></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Program
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Car Car1 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Car Car2 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Car1.<span style="color: #0000FF;">Speed</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">30</span><span style="color: #008000;">;</span>
        Car2.<span style="color: #0000FF;">Speed</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">70</span><span style="color: #008000;">;</span>
&nbsp;
        Car Car3 <span style="color: #008000;">=</span> Car1 <span style="color: #008000;">+</span> Car2<span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Car3's Speed = {0}&quot;</span>, Car3.<span style="color: #0000FF;">Speed</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">Read</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Car
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Speed<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> Car <span style="color: #0600FF;">operator</span> <span style="color: #008000;">+</span><span style="color: #000000;">&#40;</span>Car Car1, Car Car2<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Car NewCar <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        NewCar.<span style="color: #0000FF;">Speed</span> <span style="color: #008000;">=</span> Car1.<span style="color: #0000FF;">Speed</span> <span style="color: #008000;">+</span> Car2.<span style="color: #0000FF;">Speed</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">return</span> NewCar<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>As you can see, the + operator utilizes a function in the background to do its neat work. Although the concept in both the cases is same, using operators allows much greater ease. The code <b>Car Car3 = Car1 + Car2;</b> is much closer to the real world and its easier to type, isn&#8217;t it?</p>
<p>Here&#8217;s a table showing which operators can/cannot be overloaded in C#.</p>
<table class="joomlaTable">
<tr>
<th>Operators</th>
<th>Description</th>
</tr>
<tr>
<td>+ &#8211; ! ~ ++ &#8211;</td>
<td>These being unary operators take one operand and can be overloaded.</td>
</tr>
<tr>
<td>+ &#8211; * / %</td>
<td>Binary arithmetic operators take two operands and can be overloaded.</td>
</tr>
<tr>
<td>== != &lt; &gt; &lt;= &gt;=</td>
<td>Comparison operators take two parameters and can also be overloaded.</td>
</tr>
<tr>
<td>&#038;&#038; ||</td>
<td>These need to be overloaded indirectly using the &#038; and |</td>
</tr>
<tr>
<td>+= -= *= /= %=</td>
<td>Arithmetic assignment operators cannot be overloaded.</td>
</tr>
<tr>
<td>= . ?: -> new is sizeof typeof</td>
<td>These special operators cannot be overloaded.</td>
</tr>
</table>
<p><i>Note: The overloading methods must be declared as <b>public</b> and <b>static</b>.</i></p>
<h5>Overloading Prefix Unary Operators</h5>
<p>Below is the logic to accomplish unary &#8211; operator overloading. This operator changes the sign of the relative speed and is used as: <b>-&lt;Object Name&gt;</b></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Program
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Car Car1 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Car1.<span style="color: #0000FF;">RelativeSpeed</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">30</span><span style="color: #008000;">;</span>
        Car Car2 <span style="color: #008000;">=</span> <span style="color: #008000;">-</span>Car1<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Car
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> RelativeSpeed<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> Car <span style="color: #0600FF;">operator</span> <span style="color: #008000;">-</span><span style="color: #000000;">&#40;</span>Car CarObj<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Car NewCar <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        NewCar.<span style="color: #0000FF;">RelativeSpeed</span> <span style="color: #008000;">=</span> <span style="color: #008000;">-</span>CarObj.<span style="color: #0000FF;">RelativeSpeed</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">return</span> NewCar<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Notice, that the overloaded function takes only a single parameter. If another parameter was specified, this function would overload the binary &#8211; operator. Structures being user-defined data types can also be overloaded in this fashion. The only difference is that structures being value types, can be implemented in an easier way.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">struct</span> Car
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> RelativeSpeed<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> Car <span style="color: #0600FF;">operator</span> <span style="color: #008000;">-</span><span style="color: #000000;">&#40;</span>Car CarObj<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        CarObj.<span style="color: #0000FF;">RelativeSpeed</span> <span style="color: #008000;">=</span> <span style="color: #008000;">-</span>CarObj.<span style="color: #0000FF;">RelativeSpeed</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">return</span> CarObj<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>If the same implementation of the Operator &#8211; function was used in a class, both <strong>Car1</strong> and <strong>Car2</strong> would have the same RelativeSpeed of -30 after line 9. So, in the class implementation we have created a new object of the Car class.</p>
<h5>Overloading Pre &#038; Post Increment Operators</h5>
<p>Unlike, C++, C# handles the Pre &#038; Post Increment Operators by itself. Hence, we don&#8217;t need to overload them separately. Below is the implementation of the ++ operator in the <strong>Car</strong> structure.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Program
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Car Car1 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Car1.<span style="color: #0000FF;">RelativeSpeed</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">30</span><span style="color: #008000;">;</span>
        Car Car2 <span style="color: #008000;">=</span> Car1<span style="color: #008000;">++;</span>
        Car Car3 <span style="color: #008000;">=</span> <span style="color: #008000;">++</span>Car1<span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Relative speed of Car1 = {0}, Car2 = {1} and Car3 = {2}&quot;</span>
        , Car1.<span style="color: #0000FF;">RelativeSpeed</span>, Car2.<span style="color: #0000FF;">RelativeSpeed</span>, Car3.<span style="color: #0000FF;">RelativeSpeed</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">Read</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">struct</span> Car
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> RelativeSpeed<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> Car <span style="color: #0600FF;">operator</span> <span style="color: #008000;">++</span><span style="color: #000000;">&#40;</span>Car CarObj<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        CarObj.<span style="color: #0000FF;">RelativeSpeed</span><span style="color: #008000;">++;;</span>
        <span style="color: #0600FF;">return</span> CarObj<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>At line 9, the overloaded function for the object<strong> Car1</strong> is invoked. The operation being post increment, <strong>Car2</strong> gets assigned the current value of <strong>Car1</strong> which has a relative speed of 30. After this the <strong>RelativeSpeed</strong> is incremented by 1. So, <strong>Car1</strong> has a relative speed of 31 now. In the next line, pre increment results in the value of <strong>Car1</strong> to be incremented by 1 before the value is assigned to <strong>Car3</strong>. Car1&#8242;s <strong>RelativeSpeed</strong> is now equal to 32. This value gets copied in Car3. So, the output of the code is: Relative speed of Car1 = 32, Car2 = 30 and Car3 = 32.</p>
<p>If the same logic was used in the <strong>Car</strong> Class&#8217;s overloaded function, the output would be: Relative speed of Car1 = 32, Car2 = 32 and Car3 = 32. Why does this happen? As mentioned before, the class is a reference type. Hence, when we say Car1 = Car2, it implies that <strong>Car1</strong> now points to the same object in the memory as does <strong>Car2</strong>. In structures, the same statement would be equivalent to Copy the value of <strong>Car2</strong> in <strong>Car1</strong>.</p>
<h5>Arithmetic Assignment Operators</h5>
<p>Recall that, the Arithmetic Assignment operators ( += -= *= /= %= ) cannot be overloaded. This is because <strong>A += B</strong> is equivalent to<strong> A = A + B</strong>, <strong>A -= B</strong> is equivalent to <strong>A = A &#8211; B</strong> and so on. Once, you overload the binary + operator, you can perform the <strong>+=</strong> operation on the objects of the class. Same is true for the rest of the Arithmetic operators.</p>
<h5>Logical Operators</h5>
<p>Overloading Logical Operators is a bit tricky. Firstly, to overload the &#038;&#038; operator the function name should be <strong>operator &#038;</strong> and for || operator it should be <strong>operator |</strong>. Secondly, before performing these boolean short-circuit operations, the <strong>true</strong> and <strong>false</strong> operators need to be defined.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Program
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Car Car1 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Car Car2 <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Car1.<span style="color: #0000FF;">Running</span> <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
        Car2.<span style="color: #0000FF;">Running</span> <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
&nbsp;
        Car Car3 <span style="color: #008000;">=</span> Car1 <span style="color: #008000;">&amp;&amp;</span> Car2<span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>Car3.<span style="color: #0000FF;">Running</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        Console.<span style="color: #0000FF;">Read</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">class</span> Car
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span> Running<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> Car <span style="color: #0600FF;">operator</span> <span style="color: #008000;">&amp;</span><span style="color: #000000;">&#40;</span>Car Car1, Car Car2<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Car NewCar <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Car<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        NewCar.<span style="color: #0000FF;">Running</span> <span style="color: #008000;">=</span> Car1.<span style="color: #0000FF;">Running</span> <span style="color: #008000;">&amp;&amp;</span> Car2.<span style="color: #0000FF;">Running</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">return</span> NewCar<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">bool</span> <span style="color: #0600FF;">operator</span> <span style="color: #0600FF;">true</span><span style="color: #000000;">&#40;</span>Car CarObj<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> true<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">bool</span> <span style="color: #0600FF;">operator</span> <span style="color: #0600FF;">false</span><span style="color: #000000;">&#40;</span>Car CarObj<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> false<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<div class="tutnav"></div>
]]></content:encoded>
			<wfw:commentRss>http://maxotek.net/blog/csharp-tutorial-lesson-11-polymorphism-part-ii-t44.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Tutorial : Lesson 10 &#8211; Polymorphism &#8211; Part I</title>
		<link>http://maxotek.net/blog/csharp-tutorial-lesson-10-polymorphism-part-i-t43.html</link>
		<comments>http://maxotek.net/blog/csharp-tutorial-lesson-10-polymorphism-part-i-t43.html#comments</comments>
		<pubDate>Thu, 09 Aug 2007 05:58:40 +0000</pubDate>
		<dc:creator>partho</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://maxotek.net/blog/?p=43</guid>
		<description><![CDATA[The term polymorphism means multiple forms. In the world of programming, it refers to the ability of an object to exist in multiple forms. Polymorphism is one one of the key concepts of Object Oriented Programming. Why do we need polymorphism? Polymorphism is there to increase the complexity of the already complex world of programming. [...]]]></description>
			<content:encoded><![CDATA[<div class="tutnav"></div>
<p>The term polymorphism means multiple forms. In the world of programming, it refers to the ability of an object to exist in multiple forms. Polymorphism is one one of the key concepts of Object Oriented Programming.</p>
<h5>Why do we need polymorphism?</h5>
<p>Polymorphism is there to increase the complexity of the already complex world of programming. Just kidding! By using functions, we break down the program into smaller logical parts that are easier to understand, implement and thereby maintain. In this sense, the function is the smallest self sufficient (ideally) logical block of a program. As you get to know more about the real world programming, you&#8217;ll find that even these small logical blocks are often very big and rather complex. Consider the following function which is used to calculate the area of a circle from the radius entered as integer.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">double</span> CalcArea<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> Radius<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">double</span> Area <span style="color: #008000;">=</span> Math.<span style="color: #0000FF;">PI</span> <span style="color: #008000;">*</span> Radius <span style="color: #008000;">*</span> Radius<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> Area<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>This function can only handle integers as input. What if the Radius was in double? The function would fail in such a case. We can create another function named <strong>CalcAreaDouble</strong> to handle the input in double.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">double</span> CalcAreaDouble<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">double</span> Radius<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">double</span> Area <span style="color: #008000;">=</span> Math.<span style="color: #0000FF;">PI</span> <span style="color: #008000;">*</span> Radius <span style="color: #008000;">*</span> Radius<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> Area<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>While, this works, there&#8217;s something wrong about this method. The name of a function should describe(in brief) what it does and not the type of values it returns or takes as input. Both these functions do the same job, Calculate Area. Hence, they should have the same name. Thanks to Polymorphism, we can declare two functions with the same name, inside the same class.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">double</span> CalcArea<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> Radius<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">double</span> Area <span style="color: #008000;">=</span> Math.<span style="color: #0000FF;">PI</span> <span style="color: #008000;">*</span> Radius <span style="color: #008000;">*</span> Radius<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> Area<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">double</span> CalcArea<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">double</span> Radius<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">double</span> Area <span style="color: #008000;">=</span> Math.<span style="color: #0000FF;">PI</span> <span style="color: #008000;">*</span> Radius <span style="color: #008000;">*</span> Radius<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> Area<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>This is called <span id="cFunctionOverloading">function overloading</span>. For two functions with the same name to co-exist, they must follow certain rules:-</p>
<ul>
<li>The functions must differ in either the type, the sequence or the number of input parameters i.e they must have different function signatures. The CalcArea functions have different types of parameters.
<p>These two functions differ in the number of parameters:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">int</span> SumOfNum<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> Num1, <span style="color: #FF0000;">int</span> Num2<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">return</span> Num1 <span style="color: #008000;">+</span> Num2<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">int</span> SumOfNum<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> Num1, <span style="color: #FF0000;">int</span> Num2, <span style="color: #FF0000;">int</span> Num3<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">return</span> Num1 <span style="color: #008000;">+</span> Num2 <span style="color: #008000;">+</span> Num3<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>While, these have different sequence:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">float</span> SumOfNum<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> Num1, <span style="color: #FF0000;">float</span> Num2<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">return</span> Num1 <span style="color: #008000;">+</span> Num2<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">float</span> SumOfNum<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">float</span> Num1, <span style="color: #FF0000;">int</span> Num2<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">return</span> Num1 <span style="color: #008000;">+</span> Num2<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

</li>
<li>Return type has no influence on function overloading. Hence, these two functions cannot co-exist:-

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">double</span> CalcArea<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> Radius<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">double</span> Area <span style="color: #008000;">=</span> Math.<span style="color: #0000FF;">PI</span> <span style="color: #008000;">*</span> Radius <span style="color: #008000;">*</span> Radius<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> Area<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #FF0000;">int</span> CalcArea<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> Radius<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">double</span> Area <span style="color: #008000;">=</span> Math.<span style="color: #0000FF;">PI</span> <span style="color: #008000;">*</span> Radius <span style="color: #008000;">*</span> Radius<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> Area<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

</li>
</ul>
<h5>Static Polymorphism</h5>
<p>Function overloading along with operator overloading which we shall look at in the next tutorial are ways of implementing static polymorphism. Static polymorphism inturn, is one of the two types of Polymorphism, the other being Dynamic polymorphism. Also called as early binding, this concept refers to an entity existing in different forms. Just like a teacher who carries on the role of a father, a husband, a comrade besides being a teacher, the functions exist in different forms, each specializing in handling one type of role. In static polymorphism, the response to a function is decided at compile time and hence it is also called early binding.</p>
<h5>Overloading Constructors</h5>
<p>Since constructors are also functions and can be parameterized(takes parameters as input), they can be overloaded. This allows flexibility while creating an object. Consider the Rectangle class declared in the <strong>System.Drawing</strong> namespace. It can be instantiated by either of the two methods.</p>
<p><b>Method 1: Using default constructor</b></p>
<p>In this method, the bounds of the rectangle object <strong>Rect</strong> are individually set.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="csharp">Rectangle Rect <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Rectangle<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
Rect.<span style="color: #0000FF;">X</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span><span style="color: #008000;">;</span>
Rect.<span style="color: #0000FF;">Y</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">20</span><span style="color: #008000;">;</span>
Rect.<span style="color: #0000FF;">Width</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">30</span><span style="color: #008000;">;</span>
Rect.<span style="color: #0000FF;">Height</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">40</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p><b>Method 2: Using the Parametrized Constructor</b></p>

<div class="wp_syntax"><div class="code"><pre class="csharp">Rectangle Rect <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Rectangle<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">10</span>, <span style="color: #FF0000;">20</span>, <span style="color: #FF0000;">30</span>, <span style="color: #FF0000;">40</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Notice, how much easier this method is. The initialization in this case is handled by the constructor of the Rectangle class.</p>
<p>The rectangle class would have an implementation similar to this one:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">class</span> Rectangle
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> X<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Y<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Width<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Height<span style="color: #008000;">;</span>
&nbsp;
    Rectangle<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">X</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Y</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Width</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Height</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    Rectangle<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> x, <span style="color: #FF0000;">int</span> y, <span style="color: #FF0000;">int</span> width, <span style="color: #FF0000;">int</span> height<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">X</span> <span style="color: #008000;">=</span> x<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Y</span> <span style="color: #008000;">=</span> y<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Width</span> <span style="color: #008000;">=</span> width<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Height</span> <span style="color: #008000;">=</span> height<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>As you can see, the class has two overloaded constructors, one being the default constructor which takes no parameter and initializes the values of <strong>X</strong>, <strong>Y</strong>, <strong>Width</strong> and <strong>Height</strong> to 0. The other one initializes these values based on the inputs to it.</p>
<p><i>Note: This code is just to give you an idea of how the constructors are implemented. In actual fact, the rectangle class would be a lot more complex than this and would require further codes inside the constructors.</i></p>
<div class="tutnav"></div>
]]></content:encoded>
			<wfw:commentRss>http://maxotek.net/blog/csharp-tutorial-lesson-10-polymorphism-part-i-t43.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>C# Tutorial : Lesson 09 &#8211; Constructors &amp; Destructors</title>
		<link>http://maxotek.net/blog/csharp-tutorial-lesson-9-constructors-destructors-t39.html</link>
		<comments>http://maxotek.net/blog/csharp-tutorial-lesson-9-constructors-destructors-t39.html#comments</comments>
		<pubDate>Mon, 06 Aug 2007 16:50:12 +0000</pubDate>
		<dc:creator>partho</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://maxotek.net/blog/?p=39</guid>
		<description><![CDATA[The need for Initialization A class contains data members (variables) and member functions. Initializing the values of these data members is essential, at times. Take a look at the following scenarios:- 1 2 int MyNumber; Console.WriteLine&#40;&#34;My Number = {0}&#34;, MyNumber&#41;; This block of code declares a variable MyNumber and then prints it on the screen. [...]]]></description>
			<content:encoded><![CDATA[<div class="tutnav"></div>
<h5>The need for Initialization</h5>
<p>A class contains data members (variables) and member functions. Initializing the values of these data members is essential, at times. Take a look at the following scenarios:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">int</span> MyNumber<span style="color: #008000;">;</span>
Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;My Number = {0}&quot;</span>, MyNumber<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>This block of code declares a variable <strong>MyNumber</strong> and then prints it on the screen. However, when you try to execute these instructions, an error <b>Use of unassigned local variable &#8216;Product&#8217;</b> will be generated. This is because, we are trying to use the value of <strong>MyNumber</strong>, even before we have assigned it one. This is where initialization comes in. Many languages do implicit initialization based on the type of these atomic (int, char, bool, string, etc) data types. Example: <strong>0</strong> for <strong>int</strong>, <strong>false</strong> for <strong>bool</strong>, &#8220;&#8221; or NULL string for <strong>string</strong>. But, a strongly typed language like C# doesn&#8217;t. The corrected code would be as follows:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">int</span> MyNumber <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span><span style="color: #008000;">;</span>
Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;My Number = {0}&quot;</span>, MyNumber<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>Take a look at this code snippet.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">int</span> Product<span style="color: #008000;">;</span>
<span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> I <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span> I <span style="color: #008000;">&lt;=</span> <span style="color: #FF0000;">10</span><span style="color: #008000;">;</span> I<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Product <span style="color: #008000;">*=</span> I<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The product of the first 10 natural numbers is {0}&quot;</span>, Product<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>This block of code is meant to calculate the product of the first 10 natural numbers. For this, we have setup a loop running from 1 to 10 and declared a variable named <b>Product</b> to store the running product. Finally, we display the result using <strong>Console.WriteLine</strong>. Again, this block of code generates an error on line 4. This is because, we haven&#8217;t initialized the value of <b>Product</b>. The expression <strong>Product *= I</strong> is equivalent to <strong>Product = Product * I</strong>. When this expression is being evaluated for the first time, the Right Hand Side (RHS) part will be evaluated first. This generates the error because at the moment, <strong>Product</strong> has no value.</p>
<p>In the previous versions of VB (not VB .NET), the value for <strong>Product</strong> would have been automatically set to <strong>0</strong>. While, this would take care of this error, a logical error would creep in and drive the calculations crazy &#8211; the product of first 10 natural numbers = 0. To correct this, <strong>Product</strong> must be initialized to 1. In situations like these, an initialization is a must. Here&#8217;s the corrected code:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">int</span> Product <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> I <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span> I <span style="color: #008000;">&lt;=</span> <span style="color: #FF0000;">10</span><span style="color: #008000;">;</span> I<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Product <span style="color: #008000;">*=</span> I<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The product of the first 10 natural numbers is {0}&quot;</span>, Product<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<h5>Initializing Data Members</h5>
<p>Data members can be initialized in a similar fashion:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">class</span> MyClass
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">int</span> MyNumber <span style="color: #008000;">=</span> <span style="color: #FF0000;">69</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>However, its a better approach to have a method do all initializations inside a class.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">class</span> MyClass
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">int</span> MyNumber<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Initialize<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        MyNumber <span style="color: #008000;">=</span> <span style="color: #FF0000;">69</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>After instantiating the object of this class, the method <strong>Initialize</strong> would have to be called to set the initial value for MyNumber.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="csharp">MyClass ClassA <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MyClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
ClassA.<span style="color: #0000FF;">Initialize</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p>This approach has a disadvantage too. The Initialize method needs to be called explicitly following the object instantiation. This is where the constructor jumps in. To define it: A <span  id="cConstructor">Constructor</a> is a special method which bears the same name as that of the class it is in and is used for initializing the data members of the class. Summing up the important properties of the constructor:-</p>
<ul>
<li>A Method having the same name as that of the class it is defined in.</li>
<li>It does not return any value. Also, it doesn&#8217;t have a return type associated with it, not even void.</li>
<li>It is used for initializing the data members.</li>
<li>A class can have multiple constructors.</li>
<li>It is automatically invoked when the class is instantiated.</li>
</ul>
<p>Here is how the previous example would look when done with constructors.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">class</span> MyClass
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">int</span> MyNumber<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> MyClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        MyNumber <span style="color: #008000;">=</span> <span style="color: #FF0000;">69</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Now, when the class is instantiated, the method MyClass() will be automatically invoked and MyNumber will be assigned the value 69.</p>
<h5>Static &#038; Instance Constructors</h5>
<p>Constructors can either be associated with a class&#8217;s instance (object) or the class itself. Instance constructors are the ones associated with the object and are invoked when an object of the class is instantiated. They can be used to initialize the non static members of the class. The above example was that of an instance constructor.</p>
<p>Static constructors on the other hand, are invoked only once during the execution of the program and can be used to initialize the static variables.</p>
<p>Example:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> MyClass
<span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">static</span> <span style="color: #FF0000;">int</span> MyNumber<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">static</span> MyClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
	<span style="color: #000000;">&#123;</span>
		MyNumber <span style="color: #008000;">=</span> <span style="color: #FF0000;">69</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>A class can have these two constructors existing simultaneously:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="csharp">    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> MyClass
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">int</span> MyNumber<span style="color: #008000;">;</span>
        <span style="color: #FF0000;">int</span> YourNumber<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">static</span> MyClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            MyNumber <span style="color: #008000;">=</span> <span style="color: #FF0000;">69</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        MyClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            YourNumber <span style="color: #008000;">=</span> <span style="color: #FF0000;">69</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Note: Static constructors can&#8217;t be used to initialize non-static variables and Instance constructors can&#8217;t be used to initialize static variables.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="csharp">    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> MyClass
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">int</span> MyNumber<span style="color: #008000;">;</span>
        <span style="color: #FF0000;">int</span> YourNumber<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">static</span> MyClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            YourNumber <span style="color: #008000;">=</span> <span style="color: #FF0000;">69</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// Error: YourNumber is not a static member</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        MyClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            MyNumber <span style="color: #008000;">=</span> <span style="color: #FF0000;">69</span><span style="color: #008000;">;</span>  <span style="color: #008080; font-style: italic;">// Error: MyNumber is a static member</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h5 id="cParameterizedConstructors">Parameterized Constructor</h5>
<p>The instance constructors we have seen up until this point are all default constructors. They initialize the variables with hard-coded values and are hence not flexible. We can use parameterized constructors to overcome this problem. Parameterized constructors as the name suggests, take parameters with which they initialize the values of the member variables.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> ConsoleApplication1
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            MyClass ClassA <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MyClass<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">69</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> MyClass
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">int</span> MyNumber<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> MyClass<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> Number<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">MyNumber</span> <span style="color: #008000;">=</span> Number<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Multiple, parameters can be supplied by separating each of them with a comma. The <b>this</b> keyword can be used to get a reference to the current instance of a class.</p>
<h5 id="cDestructor">Destructors</h5>
<p>That which can be created, can be destroyed. Hence came the destructor which has the same name as that of the class it is in and is prefixed by a tilde (~) symbol. Destructors are automatically invoked when the instance of the class is destroyed. They are ideally used to release any memory occupied by the member objects. The .NET Framework automatically manages the memory for the atomic data types (int, string, char, etc). However, user defined data types are managed using a safe mechanism which does not release the memory occupied by an object unless all references to it are destroyed. This can be done in the class destructor. The following example, instantiates an object of the Socket class (located in the System.Net.Sockets namespace) inside the constructor and closes it inside the destructor.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="csharp">    <span style="color: #FF0000;">class</span> MyClass
    <span style="color: #000000;">&#123;</span>
        <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Net</span>.<span style="color: #0000FF;">Sockets</span>.<span style="color: #0000FF;">Socket</span> Sck<span style="color: #008000;">;</span>
&nbsp;
        MyClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
             Sck <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Socket<span style="color: #000000;">&#40;</span>AddressFamily.<span style="color: #0000FF;">InterNetwork</span>, SocketType.<span style="color: #0000FF;">Stream</span>, ProtocolType.<span style="color: #0000FF;">Tcp</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        ~MyClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Sck.<span style="color: #0000FF;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h5>Garbage Collection</h5>
<p>The .NET Framework isolates the programmers from having to handle memory requirements. Garbage collection is the process of releasing the memory occupied by unused objects. Unlike, C++ there is no delete keyword in C# and objects cannot be explicitly destroyed. This job is automatically carried out by a special program of the .NET Framework known as the Garbage collector(GC). This program periodically scans the application for objects with no references and marks them for deletion. It is the GC which determines when the destructor of an object is invoked. This way, the GC ensures that only unused objects get destroyed.</p>
<h5>Finalize() Method</h5>
<blockquote><p>This method allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. </p></blockquote>
<p><i>Source: MSDN</i></p>
<p>This method is invoked when all of the references to an object are released from the memory. It does nothing by default and needs to be overridden. However, the precise timing of when the Finalize method would be invoked cannot be predicted. The CLR utilizes a system called reference-tracing Garbage collection, where by the GC periodically looks for objects that have no references left. Once such an object is found, the CLR invokes the Finalize method for the object, following which, the memory occupied by the object is released.</p>
<h5>Dispose() Method</h5>
<p>All classes that implement the IDisposable interface must define the Dispose() method. This method is to be used to perform application-defined tasks associated with freeing, releasing, or resetting unmanaged resources like Database connections, etc. Unlike, the Finalize() method, the Dispose() method is not automatically called and it must be explicitly called when the object is no longer in needed.</p>
<p>Fore more information on the Garbage Collection process, read this <a href="http://msdn.microsoft.com/msdnmag/issues/1100/gci/">article</a> written by Jeffrey Richter.</p>
<div class="tutnav"></div>
]]></content:encoded>
			<wfw:commentRss>http://maxotek.net/blog/csharp-tutorial-lesson-9-constructors-destructors-t39.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Tutorial : Lesson 08 &#8211; Functions/Methods</title>
		<link>http://maxotek.net/blog/c-tutorial-lesson-8-functionsmethods-t38.html</link>
		<comments>http://maxotek.net/blog/c-tutorial-lesson-8-functionsmethods-t38.html#comments</comments>
		<pubDate>Mon, 23 Jul 2007 20:56:01 +0000</pubDate>
		<dc:creator>partho</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://maxotek.net/blog/?p=38</guid>
		<description><![CDATA[The programming model has gone through many refinements, each change improving upon the model. One of the early changes was the inclusion of Subroutines or Subprograms. As the names suggest, these are fragments of code within a program. They offer the following advantages:- Reduction of code duplication by offering re-usability Simplifying program logic by decomposing [...]]]></description>
			<content:encoded><![CDATA[<div class="tutnav"></div>
<p>The programming model has gone through many refinements, each change improving upon the model. One of the early changes was the inclusion of Subroutines or Subprograms. As the names suggest, these are fragments of code within a program. They offer the following advantages:-</p>
<ul>
<li>Reduction of code duplication by offering re-usability</li>
<li>Simplifying program logic by decomposing the program into smaller blocks</li>
<li>Improving readability of the program</li>
</ul>
<h5>Why do we need functions?</h5>
<p>Consider the following program:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> ConsoleApplication1
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">int</span> JoinDay<span style="color: #008000;">;</span>
&nbsp;
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Enter the day of Joining:&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            JoinDay <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">switch</span> <span style="color: #000000;">&#40;</span>JoinDay<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Joined on a Sunday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Joined on a Monday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">3</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Joined on a Tuesday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">4</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Joined on a Wednesday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">5</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Joined on a Thursday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">6</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Joined on a Friday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">7</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Joined on a Saturday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #FF0000;">int</span> ResigDay<span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Enter the Resignation Date:&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            ResigDay <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">switch</span> <span style="color: #000000;">&#40;</span>ResigDay<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Resigned on a Sunday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Resigned on a Monday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">3</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Resigned on a Tuesday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">4</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Resigned on a Wednesday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">5</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Resigned on a Thursday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">6</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Resigned on a Friday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">7</span><span style="color: #008000;">:</span>
                    Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Resigned on a Saturday&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    break<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
&nbsp;
            Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>This program displays the weekday of joining and resigning based on the day code entered by the user. While, there are no errors in the code, there is a problem &#8211; repetition of code. The switch block in the second case (Resignation Day) is more or less the same except for the prefix to the output message being <b>You Resigned on a </b>. Looping is meant to minimize code repetition, but it is not applicable everywhere. In scenarios such as these we should use functions to reduce code repetition. Below is the same program when done by using a function.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> ConsoleApplication1
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">int</span> JoinDay<span style="color: #008000;">;</span>
&nbsp;
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Enter the day of Joining:&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            JoinDay <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Joined on a {0}&quot;</span>, GetDayFromCode<span style="color: #000000;">&#40;</span>JoinDay<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #FF0000;">int</span> ResigDay<span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Enter the Resignation Date:&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            ResigDay <span style="color: #008000;">=</span> Convert.<span style="color: #0000FF;">ToInt32</span><span style="color: #000000;">&#40;</span>Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;You Resigned on a {0}&quot;</span>, GetDayFromCode<span style="color: #000000;">&#40;</span>ResigDay<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> GetDayFromCode<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> Code<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">switch</span> <span style="color: #000000;">&#40;</span>Code<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">return</span> <span style="color: #666666;">&quot;Sunday&quot;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">return</span> <span style="color: #666666;">&quot;Monday&quot;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">3</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">return</span> <span style="color: #666666;">&quot;Tuesday&quot;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">4</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">return</span> <span style="color: #666666;">&quot;Wednesday&quot;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">5</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">return</span> <span style="color: #666666;">&quot;Thursday&quot;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">6</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">return</span> <span style="color: #666666;">&quot;Friday&quot;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">case</span> <span style="color: #FF0000;">7</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">return</span> <span style="color: #666666;">&quot;Saturday&quot;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">default</span><span style="color: #008000;">:</span>
                    <span style="color: #0600FF;">return</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>We have saved 28 lines by using the function for just 2 cases &#8211; Date of Joining &#038; Resigning.</p>
<p>Note: &#8211; <em>We haven&#8217;t added provision for handling invalid day codes i.e values not belonging to the range 1 &#8211; 7.</em></p>
<p>The terms function and methods are used interchangeably. Functions are composed of statements that are grouped under a name and can be used repeatedly by just calling the function.</p>
<h5>Declaration</h5>
<p>Before we can use a function, we need to define its properties, what it does and the value that it returns. Any function declaration has two parts &#8211; Signature and Body. We will use this function as our example to study the two parts.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> SumOfTwoNumbers<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> Num1, <span style="color: #FF0000;">int</span> Num2<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">int</span> Sum <span style="color: #008000;">=</span> Num1 <span style="color: #008000;">+</span> Num2<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> Sum<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h5>Function Signature</h5>
<p><img src="/images/blog/csharp_tut_lesson_8_function_signature.png" /></p>
<p>The function signature is composed of the <strong>Return Type</strong>, <strong>Function Name</strong> and the optional <strong>Parameters</strong> and <strong>Access Specifier</strong>.</p>
<ul>
<li>
<b>Return Type</b><br />
The return type determines the type of value that the function will return. It can be any of the atomic data types (int, char, string, bool, float, etc) or the user defined types (enums, objects, structures). A function that does not return any value should have a return type of <strong>void</strong>.</li>
<li>
<b>Function Name</b><br />
The function name can be anything that follows the naming rules:-</p>
<ul>
<li>The name must begin with a letter or an underscore &#038; can be followed by a sequence of letters (A-Z), digits (0-9) or underscore (_) </li>
<li>Special Characters such as ? &#8211; * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the function name. </li>
<li>A function name must not be the same as a reserved keyword such as using, public, etc.</li>
<li>The name can contain any number of the allowed characters.</li>
<li>Functions with the same class cannot have the same name</li>
</ul>
</li>
<li><b><span id="cParameter">Parameters</span></b><br />
Functions take values as input, process it and return the output. These inputs are in the form of parameters. The parameters themselves are composed of the data type and the parameter name. The data type restricts the values that can be passed to the function (int only allows Integer values, bool allows Boolean values and so on) and the parameter name can be used like a regular variable under the function body. This variable would be initialized with the value that is passed to the function when it is invoked (called). A function can have any number of parameters each of which need to separated by a comma.
</li>
</ul>
<h5>Function Body</h5>
<p>This is where we define what the function actually does. In our case, the body is composed  of the line<b>int Sum = Num1 + Num2;</b> which does the actual calculation and <b>return Sum</b> which returns the value to the calling function. Every function (except the constructor and destructor) which doesn&#8217;t have a return type of void must return a value. The return value must comply with the data type specified in the signature.</p>
<h5>Calling/Invoking the function</h5>
<p>By calling/invoking the function, we imply using it &#8211; which results in the lines of code written inside it being executed. Calling a function is very simple. We do so by the following syntax:-</p>
<p>FunctionName(param1, param2 &#8230;);</p>
<p>In our case, it would go something like &#8211; <b>SumOfTwoNumbers(6, 9);</b>. This line will pass the execution to the function <b>SumOfTwoNumbers</b> along with the values 6 and 9 which will get copied in the variables Num1 and Num2. After this, the line <b>int Sum = Num1 + Num2;</b> will be executed and the sum of the two numbers will be stored in the variable Sum. Finally, this value will be returned to the calling function, which basically discards this value (as of now). We can store this result as <b>int MySum = SumOfTwoNumbers(6, 9);</b> or display it on screen as follows <b>Console.WriteLine(SumOfTwoNumbers(6, 9));</b>.</p>
<h5>Special Cases</h5>
<p>A parameter can have two variations &#8211; ref and out. When these prefixes are applied to any parameter, its behaviour changes. Normally, the values passed to the function are just copies of the original value and any changes made to this value have no effect on the original value. By using the ref keyword we can force the value to be passed by reference. This creates an alias of the variable which might have a different name but points to the same address in the memory. Thus, changes made to this value reflect in the original value.</p>
<p>The swap function is a trivial example of this difference:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> ConsoleApplication1
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">int</span> A <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span>, B <span style="color: #008000;">=</span> <span style="color: #FF0000;">20</span><span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The value of A = {0} and B = {1}&quot;</span>, A, B<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Swap<span style="color: #000000;">&#40;</span>A, B<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The value (after swapping) of A = {0} and B = {1}&quot;</span>, A, B<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Swap<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> A, <span style="color: #FF0000;">int</span> B<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">int</span> Temp <span style="color: #008000;">=</span> A<span style="color: #008000;">;</span>
            A <span style="color: #008000;">=</span> B<span style="color: #008000;">;</span>
            B <span style="color: #008000;">=</span> Temp<span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The value (during swapping) of A = {0} and B = {1}&quot;</span>, A, B<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>The output of the following program would be:-</p>
<p>The value of A = 10 and B = 20<br />
The value (during swapping) of A = 20 and B = 10<br />
The value (after swapping) of A = 10 and B = 20</p>
<p>As you can see, the changes made to the value of A and B inside the Swap function have no effect on the values of A and B inside the Main function. This is because both pairs of variable belong to their scopes (the Swap function and the Main Function) and are hence separate. However, by using the ref keyword, we can point the variable A inside the Main and Swap function to the same memory location (same holds for the variable B). The variable A inside the Swap function will be called an alias of the variable A inside the Main function. The alias doesn&#8217;t need to have the same name either. The alias stores the memory address of the original variable and not its value.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> ConsoleApplication1
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">int</span> A <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span>, B <span style="color: #008000;">=</span> <span style="color: #FF0000;">20</span><span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The value of A = {0} and B = {1}&quot;</span>, A, B<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Swap<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> A, <span style="color: #0600FF;">ref</span> B<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The value (after swapping) of A = {0} and B = {1}&quot;</span>, A, B<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Swap<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">int</span> A, <span style="color: #0600FF;">ref</span> <span style="color: #FF0000;">int</span> B<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">int</span> Temp <span style="color: #008000;">=</span> A<span style="color: #008000;">;</span>
            A <span style="color: #008000;">=</span> B<span style="color: #008000;">;</span>
            B <span style="color: #008000;">=</span> Temp<span style="color: #008000;">;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The value (during swapping) of A = {0} and B = {1}&quot;</span>, A, B<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Output:-</p>
<p>The value of A = 10 and B = 20<br />
The value (during swapping) of A = 20 and B = 10<br />
The value (after swapping) of A = 20 and B = 10</p>
<p>By using the ref keyword, we have made the change persistent inside the Main function.</p>
<p>Note: <em>It is necessary to specify the ref keyword during function calling.</em></p>
<p>A function can take multiple inputs but only return a single value. There might be situations when we need multiple values as output from the function. We can do this by using either the ref or the out keyword. Both of them result in references being passed. The only difference is that the out keyword passes along null values and is hence ideally suited for output purposes.</p>
<p>Note: <em>It is necessary to specify the out keyword during function calling.</em></p>
<div class="tutnav"></div>
]]></content:encoded>
			<wfw:commentRss>http://maxotek.net/blog/c-tutorial-lesson-8-functionsmethods-t38.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Tutorial : Lesson 07 &#8211; Creating Value Types &amp; Reference Types &#8211; Part II</title>
		<link>http://maxotek.net/blog/csharp-tutorial-lesson-7-creating-value-types-reference-types-part-ii-t37.html</link>
		<comments>http://maxotek.net/blog/csharp-tutorial-lesson-7-creating-value-types-reference-types-part-ii-t37.html#comments</comments>
		<pubDate>Sun, 22 Jul 2007 20:59:59 +0000</pubDate>
		<dc:creator>partho</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://maxotek.net/blog/?p=37</guid>
		<description><![CDATA[foreach statement This statement is explicitly used to traverse through arrays. The benefit of using foreach over the normal for statement is that it is not necessary to check the size of the array while using the former. Syntax:- foreach(type identifier in expression) { statement 1; statement 2; &#8230; } Suppose we have an array [...]]]></description>
			<content:encoded><![CDATA[<div class="tutnav"></div>
<h5>foreach statement</h5>
<p>This statement is explicitly used to traverse through arrays. The benefit of using <strong>foreach</strong> over the normal <strong>for</strong> statement is that it is not necessary to check the size of the array while using the former.</p>
<p>Syntax:-</p>
<p>foreach(type identifier in expression)<br />
{<br />
statement 1;<br />
statement 2;<br />
&#8230;<br />
}</p>
<p>Suppose we have an array <strong>StudentNames</strong> containing the name of all the students in a class. We need to display the name of each one of them on screen. First we will see how it can be done using the <strong>for</strong> loop.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> StudentNames <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot;Peter&quot;</span>, <span style="color: #666666;">&quot;Tony&quot;</span>, <span style="color: #666666;">&quot;Bruce&quot;</span>, <span style="color: #666666;">&quot;Scott&quot;</span>, <span style="color: #666666;">&quot;Clark&quot;</span>, <span style="color: #666666;">&quot;Kenshin&quot;</span><span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> I <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> I <span style="color: #008000;">&lt;</span> StudentNames.<span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span> I  <span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>StudentNames<span style="color: #000000;">&#91;</span>I<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Now we&#8217;ll use the <strong>foreach</strong> statement to do this.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> StudentNames <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span><span style="color: #666666;">&quot;Peter&quot;</span>, <span style="color: #666666;">&quot;Tony&quot;</span>, <span style="color: #666666;">&quot;Bruce&quot;</span>, <span style="color: #666666;">&quot;Scott&quot;</span>, <span style="color: #666666;">&quot;Clark&quot;</span>, <span style="color: #666666;">&quot;Kenshin&quot;</span><span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> StudentName <span style="color: #0600FF;">in</span> StudentNames<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span>StudentName<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<h5>Param Arrays</h5>
<p>Remember the <strong>Console.WriteLine</strong> method which outputs the result using a string format followed by the additional values as input parameters. For example: <strong>Console.WriteLine(&#8220;The sum of {0} and {1} is {2}&#8221;, Num1, Num2, Num1   Num2);</strong> would display <strong>The sum of 5 and 6 is 11</strong> for values 5 and 6 for Num1 and Num2 respectively. What is worth noting here, is that <strong>WriteLine()</strong> can take any number of parameters after the string format. So, something like this would work as well:-</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The Prime Numbers -&gt; {0}, {1}, {2}, {3}, {4}&quot;</span>, <span style="color: #FF0000;">2</span>, <span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">5</span>, <span style="color: #FF0000;">7</span>, <span style="color: #FF0000;">11</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>This is done by the <strong>param</strong> array data type. Example:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="csharp"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">int</span> Sum<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">params</span> <span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> Numbers<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #FF0000;">int</span> Sum <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
	<span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> Number <span style="color: #0600FF;">in</span> Numbers<span style="color: #000000;">&#41;</span>
	<span style="color: #000000;">&#123;</span>
		Sum  <span style="color: #008000;">=</span> Number<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
	<span style="color: #0600FF;">return</span> Sum<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>This is a function to return the sum of any number of numbers. The numbers to be summed are passed as parameters during the function call as: <strong>Sum(4, 69, 13, 99)</strong>;</p>
<p><i>Note:  param array should be the last parameter in the function signature which also means that only one param array can be used in a function. Why is this done? Consider the following function signature: <strong>public static int MyFunction(params int[] A, int C)</strong>. How would we call the function if this were to be allowed? <strong>MyFunction(1, 2, 3, 4, 5);</strong> How can the compiler determine where the values for the param array A finish? Actually, if a reverse scanning of parameters were to be done, this could be determined. But that would increase useless complexity of having to implement this along with the normal forward scanning of parameters.</i></p>
<h5>Multi Dimensional Arrays</h5>
<p>Up until now, we have only worked with Single Dimensional arrays. Now we shall see how the Multi Dimensional arrays are declared, initialized and manipulated. The pictures below show how the Single and Double Dimensional arrays are represented.</p>
<p><b>Single Dimensional Array</b></p>
<p><img src="/images/blog/csharp_tut_lesson_7_single_dimensional_array.png" /></p>
<p><b>Multi Dimensional Array</b></p>
<p><img src="/images/blog/csharp_tut_lesson_7_multi_dimensional_array.png" /></p>
<p>While, the Single Dimensional arrays are represented as a single row of elements, Double Dimensional arrays are represented by multiple rows. Similarly, arrays with 3 dimensions would be represented in 3D space along the three axes.</p>
<h5>Declaration</h5>
<p>Declaration is done by the syntax:-</p>
<p>datatype [ , ] VariableName;</p>
<p>The number of commas ( , ) inside the square brackets [ ] should be one less than the number of dimensions required for the array.</p>
<p>Example Usage:-</p>

<div class="wp_syntax"><div class="code"><pre class="csharp"><span style="color: #FF0000;">int</span> <span style="color: #000000;">&#91;</span> , <span style="color: #000000;">&#93;</span> Numbers<span style="color: #008000;">;</span></pre></div></div>

<h5>Initialization</h5>
<p>Initialization is done in a way where each row is treated like a single dimensional array. Example:-</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="csharp"><span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span>,<span style="color: #000000;">&#93;</span> Numbers <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">int</span><span style="color: #000000;">&#91;</span><span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">3</span><span style="color: #000000;">&#93;</span>
<span style="color: #000000;">&#123;</span>
	<span style="color: #000000;">&#123;</span><span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">2</span>, <span style="color: #FF0000;">3</span><span style="color: #000000;">&#125;</span>,
	<span style="color: #000000;">&#123;</span><span style="color: #FF0000;">4</span>, <span style="color: #FF0000;">5</span>, <span style="color: #FF0000;">6</span><span style="color: #000000;">&#125;</span>,
	<span style="color: #000000;">&#123;</span><span style="color: #FF0000;">7</span>, <span style="color: #FF0000;">8</span>, <span style="color: #FF0000;">9</span><span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<h5>Assigning Values</h5>
<p>Values can be assigned as:-</p>

<div class="wp_syntax"><div class="code"><pre class="csharp">Numbers<span style="color: #000000;">&#91;</span><span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">2</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">7</span><span style="color: #008000;">;</span></pre></div></div>

<h5>Array Class</h5>
<p>The <strong>Array</strong> class defined in the <strong>System</strong> namespace serves as the base class for all the arrays in the Common Language Runtime. It can be used to create, manipulate, search and sort arrays.</p>
<p>Some of the common Properties and methods are summarized below.</p>
<p><strong>Properties</strong></p>
<ul>
<li>IsFixedSize &#8211; Returns a boolean value (True / False) indicating whether the array is of Fixed Size or not.</li>
<li>IsReadOnly &#8211; Returns a boolean value (True / False) indicating whether the array is Read Only or not.</li>
<li>Length &#8211; Returns a 32-bit integer that represents the total number of elements across all dimensions in the array.</li>
<li>Rank &#8211; Returns the number of dimensions (also called the Rank) of the array.</li>
</ul>
<h5>Methods</h5>
<ul>
<li>BinarySearch &#8211; Performs the faster Binary Search algorithm on the array and returns the number if found.</li>
<li>Clear &#8211; Resets the value of the supplied range of elements in the array to the default values of the datatype:-
<ul>
<li>int &#8211; 0</li>
<li>bool &#8211; false</li>
<li>Reference Data Types &#8211; Null</li>
</ul>
</li>
<li>Copy &#8211; Copies a range of elements to another array along with type casting and boxing as required</li>
<li>CopTo &#8211; Copies all elements to the specified single dimensional array</li>
<li>Find &#8211; Searches for the given value and returns its first occurrence in the array</li>
<li>FindAll &#8211; Returns all occurrences of the searched element in the array</li>
<li>GetLength &#8211; Returns the 32 bit length of the array</li>
<li>GetValue &#8211; Returns the value of the specified item in the array</li>
<li>IndexOf &#8211; Searches for the given value and returns the index of the first position its found in</li>
<li>Resize &#8211; Resizes the array</li>
<li>Reverse &#8211; Reverses the order of the elements. (Works only on a single dimensional array)
</li>
<li>SetValue &#8211; Sets the value at the specified location of the array</li>
<li>Sort &#8211; Sorts the elements. (Works only on a single dimensional array)</li>
</ul>
<h5>Collections</h5>
<p>An integer array can only store integers. Same goes for any other array type &#8211; string, boolean, etc. <strong>Collections</strong> overcome this limitation of arrays and can store elements of different types as <strong>items</strong>. This is possible because Collections actually store references and not values. We use the <strong>System.Collections</strong>  namespace to work with collections.</p>
<p><strong>Boxing</strong> &#8211; No, not the Sport! Boxing is the automatic conversion of value types to reference types allowing them to be stored in collections.<br />
<strong>Unboxing</strong> &#8211; The reverse of the former, conversion of reference type to value type.</p>
<p>Because Collections store references, it is necessary to do the above conversions while storing and retrieving values in Collections.</p>
<p><strong>Array List</strong> &#8211; Array List is a better alternative to arrays because of the following advantages it offers over arrays. It resides in the System.Collection namespace.</p>
<ul>
<li>Resizing &#8211; Arrays cannot be resized natively. So, one has to create a new array and copy the elements of the existing one followed by rearrangement of references for this process. Array List on the other hand work on the concept of Linked List where memory is allocated and deallocated at runtime as and when required.</li>
<li>Adding an element &#8211; To add an element we need to first create a new array, copy the values before the position where the new element is to be inserted, insert the new element and then insert the remaining elements. Again, a cumbersome process for arrays. Array Lists only need to allocate memory for the new element and resolve the references of the elements on both side of the new element.</li>
<li>Deleting an element &#8211; All elements after the element to be deleted need to be shifted forward to fill up the vacancy created by the deletion. Array Lists rely on releasing the memory occupied by the element and resolving the references of the elements on both sides.</li>
</ul>
<p><strong>Common Methods used by the Array List class:-</strong></p>
<ul>
<li>Add &#8211; Adds an item at the end of the Array List</li>
<li>Clear &#8211; Removes all the items from the Array List</li>
<li>Insert &#8211; Inserts an element into the Array List at the specified position</li>
<li>Reverse &#8211; Reverses the order of all the elements or a portion of the Array List</li>
<li>Remove &#8211; Deletes the item at its first occurrence</li>
<li>TrimToSize &#8211; Sets the maximum capacity to the number of elements currently in the the Array List</li>
</ul>
<p><strong>Other Classes that the collection namespace provides are:-</strong></p>
<ul>
<li>Queue &#8211; A Collection that works on the First-In-First-Out (FIFO) rule. Here, insertion of elements occur at the rear and deletion at the front.</li>
<li>Stack &#8211; Works on the Last-In-First-Out (LIFO) rule. Both insertion and deletion occur at the top of the stack.</li>
<li>Hash Table &#8211; It uses unique keys to access/store elements in the collection.</li>
</ul>
<div class="tutnav"></div>
]]></content:encoded>
			<wfw:commentRss>http://maxotek.net/blog/csharp-tutorial-lesson-7-creating-value-types-reference-types-part-ii-t37.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

