<?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>Daily Morn by Raymond Li &#187; C#</title>
	<atom:link href="http://rayli.net/blog/tag/csharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://rayli.net/blog</link>
	<description></description>
	<lastBuildDate>Sun, 22 Jan 2012 02:52:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Binary serialization in C#</title>
		<link>http://rayli.net/blog/2011/03/binary-serialization-in-c-sharp/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=binary-serialization-in-c-sharp</link>
		<comments>http://rayli.net/blog/2011/03/binary-serialization-in-c-sharp/#comments</comments>
		<pubDate>Sun, 06 Mar 2011 02:20:22 +0000</pubDate>
		<dc:creator>Raymond Li</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://rayli.net/blog/?p=748</guid>
		<description><![CDATA[Serializing an object into a binary file is an easy and fast way to persist your objects. If binary serialization is used to cache objects normally read from an XML file, a database or some other file format, you&#8217;ll get even more benefits. After incorporating binary serialization into a C# application that loaded data from [...]]]></description>
			<content:encoded><![CDATA[<p>Serializing an object into a binary file is an easy and fast way to persist your objects. If binary serialization is used to cache objects normally read from an XML file, a database or some other file format, you&#8217;ll get even more benefits.</p>
<p><span id="more-748"></span></p>
<p>After incorporating binary serialization into a C# application that loaded data from an Excel spreadsheet, I was able to get a 33% decrease in execution time by caching the generated object into a binary file. It&#8217;s a quick-and-dirty way to get a speed increase especially when you&#8217;re loading a lot of external data that changes, but doesn&#8217;t change frequently.</p>
<p>The first step for serializing a class into a binary file is to mark the class as <em>Serializable</em>.</p>
<pre class="brush: csharp; title: ; notranslate">
[Serializable]
public class YourClass
{
	// your class definition.
}
</pre>
<p>Now that your class is ready to be serialized, you can use <em>ObjectSerializer</em>. The <em>ObjectSerializer </em>class below allows anyone to serialize an object into a binary file. Serializing or de-serializing a class marked with the <em>[Serializable]</em> attribute takes no more than 3 lines of C# code.</p>
<pre class="brush: csharp; title: ; notranslate">
public class ObjectSerializer&lt;T&gt;
{
	protected IFormatter iformatter;

	public ObjectSerializer()
	{
		this.iformatter = new BinaryFormatter();
	}

	public T GetSerializedObject(string filename)
	{
		if (File.Exists(filename))
		{
			Stream inStream = new FileStream(
				filename,
				FileMode.Open,
				FileAccess.Read,
				FileShare.Read);
			T obj = (T)this.iformatter.Deserialize(inStream);
			inStream.Close();
			return obj;
		}
		return default(T);
	}

	public void SaveSerializedObject(T obj, string filename)
	{
		Stream outStream = new FileStream(
			filename,
			FileMode.Create,
			FileAccess.Write,
			FileShare.None);
		this.iformatter.Serialize(outStream, obj);
		outStream.Close();
	}
}
</pre>
<p>To serialize an object using <em>ObjectSerializer</em>, first instantiate the <em>ObjectSerializer </em>class. Then use the <em>SaveSerialziedObject()</em> method to serialize the object.</p>
<pre class="brush: csharp; title: ; notranslate">
YourClass yourObject = new YourClass();
ObjectSerializer&lt;YourClass&gt; objSerializer =
	new ObjectSerializer&lt;YourClass&gt;();

// serializes yourClass to SomeFilename.bin.
objSerializer.SaveSerializedObject(yourObject, &quot;SomeFilename.bin&quot;);
</pre>
<p>To deserialize the binary file generated from the previous operation, instantiate the <em>ObjectSerializer </em>class. Then use the <em>GetSerializedObject()</em> method to retrieve the original object.</p>
<pre class="brush: csharp; title: ; notranslate">
ObjectSerializer&lt;YourClass&gt; objSerializer =
	new ObjectSerializer&lt;YourClass&gt;();

// deserializes yourClass from SomeFilename.bin.
YourClass yourObjectFromFile =
	objSerializer.GetSerializedObject(&quot;SomeFilename.bin&quot;);
</pre>
<p>And there you have it&#8230; quick-and-dirty binary serialization in C#!</p>
]]></content:encoded>
			<wfw:commentRss>http://rayli.net/blog/2011/03/binary-serialization-in-c-sharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Overload the array square bracket operator in C#</title>
		<link>http://rayli.net/blog/2008/11/overload-the-array-square-bracket-operator-in-c/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=overload-the-array-square-bracket-operator-in-c</link>
		<comments>http://rayli.net/blog/2008/11/overload-the-array-square-bracket-operator-in-c/#comments</comments>
		<pubDate>Thu, 13 Nov 2008 10:35:02 +0000</pubDate>
		<dc:creator>Raymond Li</dc:creator>
				<category><![CDATA[Popular]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://rayli.net/blog/?p=96</guid>
		<description><![CDATA[Although operator overloading is possible in C# (just like in C++), overloading the array square bracket operator is by definition not possible.  However, C# provides an alternative called indexers.  This is directly from the Microsoft C# Reference for the [] Operator: The array indexing operator cannot be overloaded; however, types can define indexers, and properties [...]]]></description>
			<content:encoded><![CDATA[<p>Although operator overloading is possible in C# (<a title="Operator   Overloading in C++" href="http://www.philosophicalgeek.com/2002/08/14/operator-overloading-in-c/">just like in C++</a>), overloading the array square bracket operator is by definition not possible.  However, C# provides an alternative called <a title="Indexers Tutorial" href="http://msdn.microsoft.com/en-us/library/aa288465(VS.71).aspx">indexers</a>.  This is directly from the Microsoft C# Reference for the <a title="[]   Operator (C# Reference)" href="http://msdn.microsoft.com/en-us/library/a3hd7ste.aspx">[] Operator</a>:</p>
<p><span id="more-96"></span></p>
<blockquote><p>The array indexing operator cannot be overloaded; however, types can define indexers, and properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indexes, but indexer parameters can be declared to be of any type, unlike array indexes, which must be integral.</p></blockquote>
<p>The syntax for indexers resembles the C# syntax for properties rather than its syntax for operator overloading. Here&#8217;s a quick snippet for providing array-like access to a List you&#8217;d like to keep hidden within a class:</p>
<pre class="brush: csharp; title: ; notranslate">
// overloads the square brackets to provide array-like access.
public T this[int i]
{
    get { return this.List[i]; }
    set { this.List[i] = value; }
}
</pre>
<p>Worked for me, and hopefully it works just as well for you!</p>
<p>UPDATE: As I do a quick search now, this Stack Overflow <a title="How   do I overload the square-bracket operator in C#?" href="http://stackoverflow.com/questions/287928/how-do-i-overload-the-square-bracket-operator-in-c">post</a> just turned up.</p>
]]></content:encoded>
			<wfw:commentRss>http://rayli.net/blog/2008/11/overload-the-array-square-bracket-operator-in-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Why does an abstract class need to implement interface methods?</title>
		<link>http://rayli.net/blog/2008/09/why-does-an-abstract-class-need-to-implement-interface-methods/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-does-an-abstract-class-need-to-implement-interface-methods</link>
		<comments>http://rayli.net/blog/2008/09/why-does-an-abstract-class-need-to-implement-interface-methods/#comments</comments>
		<pubDate>Sun, 28 Sep 2008 15:28:17 +0000</pubDate>
		<dc:creator>Raymond Li</dc:creator>
				<category><![CDATA[Popular]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://rayli.net/blog/?p=77</guid>
		<description><![CDATA[In a comment for a previous post (Top 10 differences between Java and C#), John P. Wood wrote: As a (primarily) Java developer, I’ve also noticed that C# handles abstract classes that implement interfaces differently. In Java, an abstract class can implement an interface, and not provide implementations of all of the interface’s methods.  It [...]]]></description>
			<content:encoded><![CDATA[<p>In a comment for a previous post (<a title="Top 10 differences between Java and C#" href="http://rayli.net/blog/2008/04/top-10-differences-between-java-and-c/">Top 10 differences between Java and C#</a>), John P. Wood wrote:</p>
<blockquote><p>As a (primarily) Java developer, I’ve also noticed that C# handles abstract classes that implement interfaces differently. In Java, an abstract class can implement an interface, and not provide implementations of all of the interface’s methods.  It is the responsibility of the first concrete class that has that abstract class as an ancestor to implement all of the methods in the interface.</p>
<p><span id="more-77"></span>C# on the other hand seems to require that the abstract class provide implementations for all of the methods on the interface. Even if that implementation is just a method signature.</p></blockquote>
<p>Like these 3 posts (<a title="Interfaces (C# Programming Guide)" href="http://msdn.microsoft.com/en-us/library/ms173156.aspx" target="_self">1</a> (bottom), <a title="Abstract/Interface question" href="http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/f1f8106c-d2e8-436c-9ee9-6b3e6731d185/" target="_self">2</a>, <a title="Why do abstract classes need to   implement interface members?" href="http://jelle.druyts.net/CommentView.aspx?guid=fe5e801e-71e5-474e-8235-01b2ad14ff68" target="_self">3</a>), I am struggling with why the Microsoft Team chose to do this.  Why ask the developer to write a little stub for the interface method, when the abstract class has no intention of implementing it at all?</p>
<p>I believe it&#8217;s a natural artifact of virtual and non-virtual methods in C# (<a title="Gotcha #2 - I can’t override!?" href="http://rayli.net/blog/2008/04/top-10-differences-between-java-and-c/#override">gotcha #2</a>).  In Java, methods are virtual by default (as far as I&#8217;m aware, Java doesn&#8217;t support non-virtual methods).  However, C# (being derived from C++) does support non-virtual methods.  When an abstract class implements an interface in C#, you are given the chance to describe the interface methods as abstract, virtual or non-virtual.  Here&#8217;s exactly what each options means:</p>
<ol>
<li><strong>abstract </strong>- No attempt at an implementation is made in the abstract class.  It&#8217;s up to the first concrete class to provide an implementation.  As a side note, defining a method as <em>abstract </em>implicitly defines it as <em>virtual</em>.  If this weren&#8217;t the case, you wouldn&#8217;t be able to override it in the child class which defeats the purpose of an abstract method.</li>
<li><strong>virtual </strong>- An attempt was made in the abstract class to implement this method, but the child class has the option of overriding it and providing its own implementation.</li>
<li><strong>non-virtual</strong> &#8211; Again, an attempt was made at an implementation in the abstract class.  However, the child class cannot override this method.  If a child class defines a method with the same name, the method will not be associated with the interface implemented in the abstract class.  The method associated with the interface is the <em>non-virtual</em> method defined by the abstract class.</li>
</ol>
<p>Java can do options 1 and 2, but it lacks option 3.  Java could define the method as <em>final</em> to prevent it from being overriden, but this is slightly different than <em>non-virtual</em>.  The <em>final </em>keyword is more along the lines of <em>seal</em> in C#.  By allowing an option 3, C# provides finer control over how interfaces are inherited.  If C# went the route of Java and permitted abstract classes to put off interface method definitions, these methods would need to be <em>virtual </em>by default.  However, this would be inconsistent with C# methods being <em>non-virtual</em> by default.</p>
<p>In a nutshell, the C# developer is forced in the abstract class to decide exactly which of the three options to assign to the interface method.  Anyway, that&#8217;s my best guess&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://rayli.net/blog/2008/09/why-does-an-abstract-class-need-to-implement-interface-methods/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Portrait vs landscape, CRF design for a tablet PC</title>
		<link>http://rayli.net/blog/2008/08/portrait-vs-landscape-crf-design-for-a-tablet-pc/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=portrait-vs-landscape-crf-design-for-a-tablet-pc</link>
		<comments>http://rayli.net/blog/2008/08/portrait-vs-landscape-crf-design-for-a-tablet-pc/#comments</comments>
		<pubDate>Thu, 14 Aug 2008 16:18:21 +0000</pubDate>
		<dc:creator>Raymond Li</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CRF Design]]></category>
		<category><![CDATA[Tablet PC]]></category>

		<guid isPermaLink="false">http://rayli.net/blog/?p=72</guid>
		<description><![CDATA[How do you systematically make use of the varied Tablet PC screen resolution dimensions using C#? Designing a CRF specifically for a Tablet PC can be a challenging experience, but it can also be one of the most rewarding. The Tablet PC is very similar to a traditional desktop computer or a laptop.  As I [...]]]></description>
			<content:encoded><![CDATA[<p><em><a href="http://rayli.net/ref/2008-08/hp_tablet_pc_tc1100.jpg"><img class="alignleft" title="HP Tablet PC (convertible)" src="/ref/2008-08/hp_tablet_pc_tc1100.jpg" alt="HP Tablet PC (convertible)" width="150" height="141" /></a>How do you systematically make use of the varied Tablet PC screen resolution dimensions using C#?</em></p>
<p>Designing a CRF specifically for a Tablet PC can be a challenging experience, but it can also be one of the most rewarding.</p>
<p>The Tablet PC is very similar to a traditional desktop computer or a laptop.  As I write this entry, most Tablet PCs are running some variant of Windows.  Whether it&#8217;s Windows XP Tablet PC Edition or Vista (which has built-in support for Tablet PC specific functionality), you&#8217;re basically dealing with a Windows machine and you can pretty much treat it as such&#8230;  almost.</p>
<p><span id="more-72"></span>Maybe it&#8217;s not so much the variety.  One of my biggest obstacles was that the dimensions change.  They don&#8217;t change just once in a while (like when the resolution changes when you connect your laptop to a TV), they can change many times during a single session!</p>
<p>For example, convertible Tablet PCs (like the one in the image above) provide the ability to change from portrait to landscape and back again all in seconds.  In addition, most Tablet PCs come in screen dimensions that are either wider or taller depending on whether it&#8217;s in slate mode or the more traditional notebook mode.  Taking advantage of a taller or wider screen is going to be the topic of a future post, but let&#8217;s say you have a layout for making use of the added height or width, how do you know when to use which?</p>
<p>The first step is determining whether the screen dimensions are in portrait (slate) mode or landscape (notebook) mode.  Here are two straight-forward methods for determining which mode the Tablet PC is using:</p>
<pre class="brush: csharp; title: ; notranslate">
public bool IsPortrait()
{
    return Screen.PrimaryScreen.Bounds.Height &gt;
        Screen.PrimaryScreen.Bounds.Width;
}

public bool IsLandscape()
{
    return !this.IsPortrait();
}
</pre>
<p>We can setup a thread that calls one of these methods at specified intervals (polling solution), or we can leverage the .NET event architecture so that our application responds to dimension changes. Leveraging the event architecture is intuitively more efficient and more reliable, so add this to your <em>Form_Load()</em> method:</p>
<pre class="brush: csharp; title: ; notranslate">
Microsoft.Win32.SystemEvents.DisplaySettingsChanged +=
    new EventHandler(SystemEvents_DisplaySettingsChanged);
</pre>
<p>Now, define the event handler:</p>
<pre class="brush: csharp; title: ; notranslate">
void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
{
    if (ScreenProperties.IsPortrait())
        // do portrait handling
    else
        // do landscape handling
}
</pre>
<p>And just like that, your form is now responding to screen resolution dimension changes!</p>
]]></content:encoded>
			<wfw:commentRss>http://rayli.net/blog/2008/08/portrait-vs-landscape-crf-design-for-a-tablet-pc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quick and dirty &#8220;dirty checking&#8221; for Windows form, C#</title>
		<link>http://rayli.net/blog/2008/07/quick-and-dirty-dirty-checking-for-windows-form-c/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=quick-and-dirty-dirty-checking-for-windows-form-c</link>
		<comments>http://rayli.net/blog/2008/07/quick-and-dirty-dirty-checking-for-windows-form-c/#comments</comments>
		<pubDate>Wed, 30 Jul 2008 14:26:38 +0000</pubDate>
		<dc:creator>Raymond Li</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CRF Design]]></category>

		<guid isPermaLink="false">http://rayli.net/blog/?p=67</guid>
		<description><![CDATA[While designing a CRF, little short-cuts can save you lots and lots of time.  This time-saver is straight-forward code-wise and should fit right into your C# code without much modification. During CRF design time, I often have CRFs that have dozens and dozens of input controls (radio buttons, dropdowns, listboxes, textboxes&#8230;).  I&#8217;d like to add [...]]]></description>
			<content:encoded><![CDATA[<p>While designing a CRF, little short-cuts can save you lots and lots of time.  This time-saver is straight-forward code-wise and should fit right into your C# code without much modification.</p>
<p>During CRF design time, I often have CRFs that have dozens and dozens of input controls (radio buttons, dropdowns, listboxes, textboxes&#8230;).  I&#8217;d like to add <em>OnChange</em> handlers to all of these input controls so that I know when a change has been made. Basically, what it comes down to is I want to know when the form is dirty, but I don&#8217;t want to add all the handlers by hand.  Fortunately, I didn&#8217;t have to and neither do you!</p>
<p><span id="more-67"></span>The code below is a recursive function which traverses the Control tree.  Whenever it locates a control that can be classified as an input control, it attaches an event handler.</p>
<pre class="brush: csharp; title: ; notranslate">void  AddOnChangeHandlerToInputControls(Control ctrl)
{
    foreach (Control subctrl in ctrl.Controls)
    {
        if (subctrl is TextBox)
            ((TextBox)subctrl).TextChanged +=
                new EventHandler(InputControls_OnChange);
        else if(subctrl is CheckBox)
            ((CheckBox)subctrl).CheckedChanged +=
                new EventHandler(InputControls_OnChange);
        else if(subctrl is RadioButton)
            ((RadioButton)subctrl).CheckedChanged +=
                new EventHandler(InputControls_OnChange);
        else if(subctrl is ListBox)
            ((ListBox)subctrl).SelectedIndexChanged +=
                new EventHandler(InputControls_OnChange);
        else if(subctrl is ComboBox)
            ((ComboBox)subctrl).SelectedIndexChanged +=
                new EventHandler(InputControls_OnChange);
        else
        {
            if (subctrl.Controls.Count &gt; 0)
                this.AddOnChangeHandlerToInputControls(subctrl);
        }
    }
}</pre>
<p>Keep in mind the recursion is necessary, because the <em>Controls</em> property field only lists a control&#8217;s immediate children. Those immediate children may have children of their own. That&#8217;s right&#8230; exactly like a family tree! The use of recursion creates an elegant way to traverse the control&#8217;s control tree.</p>
<p>I&#8217;ve only picked up on the simplest input controls. It should be straight-forward to extend this for other controls like a <em>DateTimePicker</em> or a <em>CheckedListBox</em> (although the <em>CheckedListBox</em> is a little tricky because it uses a different type of event handler).</p>
<pre class="brush: csharp; title: ; notranslate">void InputControls_OnChange(object sender,  ItemCheckEventArgs e)
{
    // Do something to indicate the form is dirty like:
    // this.formIsDirty = true;
}</pre>
<p>All the event handler does is set a flag which indicates the form is dirty.  How you process the dirty flag is up to you, and there you have it! Hopefully, you&#8217;ve saved a few hours of manually adding event handlers!</p>
]]></content:encoded>
			<wfw:commentRss>http://rayli.net/blog/2008/07/quick-and-dirty-dirty-checking-for-windows-form-c/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Top 10 differences between Java and C#</title>
		<link>http://rayli.net/blog/2008/04/top-10-differences-between-java-and-c/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=top-10-differences-between-java-and-c</link>
		<comments>http://rayli.net/blog/2008/04/top-10-differences-between-java-and-c/#comments</comments>
		<pubDate>Wed, 02 Apr 2008 22:10:25 +0000</pubDate>
		<dc:creator>Raymond Li</dc:creator>
				<category><![CDATA[Popular]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://rayli.net/blog/?p=56</guid>
		<description><![CDATA[My latest transition from Java to C# left me scratching my head and scrambling to find the differences.  Don&#8217;t get me wrong &#8212; they are very similar, but some key syntax and philosophical differences set these two languages apart.  Below are my top 10 differences that I wish someone told me before I pulled out [...]]]></description>
			<content:encoded><![CDATA[<p>My latest transition from Java to C# left me scratching my head and scrambling to find the differences.  Don&#8217;t get me wrong &#8212; they are very similar, but some key syntax and philosophical differences set these two languages apart.  Below are my top 10 differences that I wish someone told me before I pulled out yet more hair.</p>
<p><a href="#standard-output"><span id="more-56"></span>Gotcha #10 &#8211; Give me my standard output!</a><br />
<a href="#namespaces">Gotcha #9 &#8211; Namespaces == Freedom</a><br />
<a href="#super">Gotcha #8 &#8211; What happened to <em>super</em>?</a><br />
<a href="#constructors">Gotcha #7 &#8211; Chaining constructors to a base constructor</a><br />
<a href="#inherit">Gotcha #6 &#8211; Dagnabit, how do I inherit?</a><br />
<a href="#constants">Gotcha #5 &#8211; Why don&#8217;t constants remain constant?</a><br />
<a href="#hashtable">Gotcha #4 &#8211; Where is ArrayList, Vector or Hashtable?</a><br />
<a href="#properties">Gotcha #3 &#8211; Of Accessors and Mutators (Getters and Setters)</a><br />
<a href="#override">Gotcha #2 &#8211; I can&#8217;t override!?</a><br />
<a href="#objects">And the #1 gotcha&#8230;</a></p>
<h3><a name="standard-output"></a>Gotcha #10 &#8211; Give me my standard output!</h3>
<p>This may not seem like a big deal, but when I&#8217;m first getting my head in a language, I want to be able to debug.  With everything so new and shiny, I don&#8217;t want to hear about the debugger yet, I don&#8217;t care about the fancy message boxes, just tell me how to get something on standard output!</p>
<p>In C#, the code looks like this:</p>
<pre class="brush: csharp; title: ; notranslate">Console.WriteLine(&quot;your string here&quot;);</pre>
<h3><a name="namespaces"></a>Gotcha #9 &#8211; Namespaces ==  Freedom</h3>
<p>In Java, the package hierarchical structure mirrored the directory hierarchical structure.  This made sense to a degree, but then why didn&#8217;t Sun just auto-derive the package structure?  Anyway, Microsoft has freed us from this constraint.  The C# package structure is defined using namespaces (just like Java), but the namespaces do NOT have to reflect the directory structure.</p>
<h3><a name="super"></a>Gotcha #8 &#8211; What happened to <em>super</em>?</h3>
<p>Slight renaming of keywords drives me bonkers!  Substitute Java&#8217;s <em>super</em> keyword with <em>base</em>.</p>
<h3><a name="constructors"></a>Gotcha #7 &#8211; Chaining constructors to a base constructor</h3>
<p>In Java, I often created a set of constructors with differing parameters that all reference a common all-powerful constructor.  In other words, I created a set of overloaded constructors that basically just called a constructor that did the bulk of the work.  This is called constructor chaining and normally leads to easier to maintain code.  In Java, the <em>this(&#8230;)</em> statement is used to call the constructor.  In C#, this is done right up in the method signature.</p>
<pre class="brush: csharp; title: ; notranslate">public MyConstructor(int i) : this(i, -1)
{
    ...
}

public MyConstructor(int i, int j)
{
    ...
}
</pre>
<h3><a name="inherit"></a>Gotcha #6 &#8211; Dagnabit, how do I inherit?</h3>
<p>In Java, the keyword <em>extends </em>is used to inherit from a parent class, and the keyword <em>implements </em>is used to inherit an interface.  In C#, the distinction does not exist and it&#8217;s all done in the method signature.</p>
<pre class="brush: csharp; title: ; notranslate">public class MyClass : MyParentClass
{
    ...
}</pre>
<h3><a name="constants"></a>Gotcha #5 &#8211; Why don&#8217;t constants remain constant?</h3>
<p>Well of course they do!  Just not among different languages.  In Java, I normally defined global constants using <em>public static final</em>.  In C#, the <em>static</em> keyword does exist (<em>final</em> does not), but you can define constants like this:</p>
<pre class="brush: csharp; title: ; notranslate">public const MyConstant = 101;</pre>
<p>When the constant needs to be initialized at run-time (for example in a constructor), use the <em>readonly</em> keyword instead of <em>const</em>.</p>
<h3><a name="hashtable"></a>Gotcha #4 &#8211; Where is ArrayList, Vector or Hashtable?<strong><br />
</strong></h3>
<p>In Java, these guys were my staples.  Pre-built dynamic arrays and look-up tables decrease development time and makes my life a whole lot easier, but where are they in C#? C# has an <em>ArrayList</em>, but it doesn&#8217;t make use of generics. Instead, I like to use:</p>
<pre class="brush: csharp; title: ; notranslate">System.Collections.Generic.List&lt;&gt;</pre>
<p>Unfortunately, <em>List&lt;&gt;</em> is not thread-safe (C#&#8217;s <em>ArrayList</em> and Java&#8217;s <em>Vector</em> are thread-safe). C# also has a <em>Hashtable</em>; the generic version is:</p>
<pre class="brush: csharp; title: ; notranslate">System.Collections.Generic.Dictionary&lt;&gt;</pre>
<h3><a name="properties"></a>Gotcha #3 &#8211; Of Accessors and Mutators (Getters and Setters)</h3>
<p>As long as methods exist in classes, accessors and mutators will exist.  However, C# largely replaces them with class properties. Instead of the traditional <em>getSomeInteger()</em> and <em>setSomeInteger()</em>, we use properties!</p>
<pre class="brush: csharp; title: ; notranslate">public class SomeClass
{
    int someInteger = 42;

    public int SomeInteger
    {
        get { return this.someInteger; }
        set { this.someInteger = value; }
    }

    public void Main(string[] args)
    {
        SomeClass c = new SomeClass();
        Console.WriteLine(c.SomeInteger);
        c.SomeInteger = 420;
    }
}</pre>
<p><em>this.someInteger</em> is a class variable, and <em>value</em> is the new integer.</p>
<h3><a name="override"></a>Gotcha #2 &#8211; I can&#8217;t override!?</h3>
<p>At this point, we&#8217;ve transcended the syntax differences and we&#8217;ve entered into more philosophical choices that the Microsoft team made. In Java, all methods are by default virtual and you can override them. In C#, all methods are non-virtual. To override a method in the parent class, make sure the method of the parent class is defined as virtual using the <em>virtual</em> keyword.</p>
<pre class="brush: csharp; title: ; notranslate">class MyParentClass
{
    public virtual void MyMethod() { ... }
}</pre>
<p>In the child class, the method must use the <em>override</em> keyword.</p>
<pre class="brush: csharp; title: ; notranslate">class MyChildClass : MyParentClass
{
    public override void MyMethod() { ... }
}</pre>
<h3><a name="objects"></a>And the #1 gotcha&#8230;</h3>
<p>I remember when I first learned Java, and everyone was saying how Java made everything an object. How Java forced you to make classes for everything. This turns out to be partially true. It is necessary to make classes.  However, primitives are not objects. In C#, even what were considered primitives in Java are objects in C#.  Absolutely everything descends from System.Object.  This choice by the C# team allows for greater consistency and for such things as a cleaner implementation of automatic boxing/unboxing.</p>
]]></content:encoded>
			<wfw:commentRss>http://rayli.net/blog/2008/04/top-10-differences-between-java-and-c/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
	</channel>
</rss>

