<?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>DevtheWeb.NET &#187; C#</title>
	<atom:link href="http://www.devtheweb.net/blog/tag/csharp/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.devtheweb.net/blog</link>
	<description></description>
	<lastBuildDate>Tue, 06 Dec 2011 19:25:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>C# Bad Code Examples</title>
		<link>http://www.devtheweb.net/blog/2010/08/27/csharp-bad-code-examples/</link>
		<comments>http://www.devtheweb.net/blog/2010/08/27/csharp-bad-code-examples/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 07:28:10 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.devtheweb.net/blog/?p=1243</guid>
		<description><![CDATA[After the success of PHP Bad Code Examples, I decided to write another one about bad code examples, but this time it&#8217;s about C# Enjoy: Example 1. /// &#60;summary&#62; /// Returns current UTC time /// &#60;/summary&#62; /// &#60;returns&#62;&#60;/returns&#62; public static DateTime GetCurrentTimeUtc() { DateTime dt = DateTime.UtcNow; return dt; } Example 2. bool value; if(value.ToString.Length() [...]]]></description>
			<content:encoded><![CDATA[<p>After the success of <a title="PHP Bad Code Examples" href="http://www.devtheweb.net/blog/2010/08/18/php-bad-code-examples/" target="_blank">PHP Bad Code Examples</a>, I decided to write another one about bad code examples, but this time it&#8217;s about C# <img src='http://www.devtheweb.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Enjoy:</p>
<p><strong>Example 1</strong>.</p>
<pre><code>/// &lt;summary&gt;
/// Returns current UTC time
/// &lt;/summary&gt;
/// &lt;returns&gt;&lt;/returns&gt;
public static DateTime GetCurrentTimeUtc()
{
       DateTime dt = DateTime.UtcNow;
       return dt;
}</code></pre>
<p><strong>Example 2</strong>.</p>
<pre><code>bool value;
if(value.ToString.Length() == 4)
  return true;
else if(value.ToString.Length() == 5)
  return false;

else
  return !true &amp;&amp; !false;</code></pre>
<p><strong>Example 3</strong>.</p>
<pre><code>private void UpdateLabel(string str)
{
   if (str == "!0123clear3210!")
   {
       textBox1.Clear();
       return;
   }
   textBox1.AppendText(str);
}</code></pre>
<p><strong>Example 4</strong>.</p>
<pre><code>if ((armid == "3504000036") || (armid == "3504000034"))
{
    if (armid == "3504000036")
    {
       PlaceSave = "3243100001";
    }
    if (armid == "3504000034")
    {
       PlaceSave = "2311030001";
    }
}</code></pre>
<p><strong>Example 5</strong>.</p>
<pre><code>void delete_ServerClick(object sender, ImageClickEventArgs e)
{
  Parent.FindControl(ID).Visible = false;
}</code></pre>
<p><strong>Example 6</strong>.</p>
<pre><code>int a=0;
if (a != 0)
{
 a=0;
}
else a=0;</code></pre>
<p><strong>Example 7</strong>.</p>
<pre><code>bool exitstatus = true;
if (!extremalexit) { exitstatus = true; }</code></pre>
<p><strong>Example 8</strong>.</p>
<pre><code>if (a == null == false) {
}</code></pre>
<p><strong>Example 9</strong>.</p>
<pre><code>try
{
    ...
    if (obj == null)
    {
        LogManager.GetLogger("Log").Warn(msg);
        throw new SoapException("Object not found", SoapException.ServerFaultCode);
    }
}
catch (Exception ex)
{
    LogManager.GetLogger("Log").Error(msg, ex);
    throw new SoapException("Object not found, SoapException.ServerFaultCode, ex);
}</code></pre>
<p><strong><strong>Example 1</strong>0.</strong></p>
<pre><code>protected string TryToUpper(string text)
{
      StringBuilder sb = new StringBuilder();
      foreach(char t in text)
      {
      	try
            {
            	sb.Append(t.ToString().ToUpper());
            }
            catch
            {
            	sb.Append(t.ToString());
            }
      }
      return sb.ToString();
}</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.devtheweb.net/blog/2010/08/27/csharp-bad-code-examples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Things you probably didn’t know about C# &#8211; Part 2</title>
		<link>http://www.devtheweb.net/blog/2010/03/04/things-you-probably-didnt-know-about-csharp-part-2/</link>
		<comments>http://www.devtheweb.net/blog/2010/03/04/things-you-probably-didnt-know-about-csharp-part-2/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 09:10:44 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.devtheweb.net/blog/?p=1140</guid>
		<description><![CDATA[After a post about Things you probably didn’t know about C#, here’s a new post from the series: 1. If you want to exit you app without calling any finalizers or finally blocks use: Environment.FailFast(); 2. Instead of sting filePath = directoryPath + &#8220;\&#8221; + filename; you can use: sting filePath = System.IO.Path.Combine(directoryPath, filename); 3. [...]]]></description>
			<content:encoded><![CDATA[<p>After a post about <a href="http://www.devtheweb.net/blog/2010/02/25/things-you-probably-didnt-know-about-csharp/" target="_blank">Things you probably didn’t know about C#</a>, here’s a new post from the series:</p>
<p>1. If you want to exit you app without calling any finalizers or finally blocks use:</p>
<p>Environment.FailFast();</p>
<p>2. Instead of</p>
<p>sting filePath = directoryPath + &#8220;\&#8221; + filename;</p>
<p>you can use:</p>
<p>sting filePath = System.IO.Path.Combine(directoryPath, filename);</p>
<div style="float:left; margin-right:5px;"><!--adsense--></div>
<p>3. Forget about &#8220;rn&#8221; for new line, you can use Environment.NewLine instead. It&#8217;s better because it&#8217;s system independent</p>
<p>4. You can create a typed reference from a variable:</p>
<p>int i = 100;</p>
<p>TypedReference typeRef = __makeref(i);</p>
<p>5. From the example above, you can extract the original type:</p>
<p>Type type = __reftype(typeRef);</p>
<p>6. You can extract the value from TypedReference:</p>
<p>int j = __refvalue(typeRef, int);</p>
<p>7. You can use the &#8216;@&#8217; character in the beginning of variable names. It&#8217;s suitable to be used for vars:</p>
<p>var @obj = new object();</p>
<p>8. If you want the garbage collector to collect some object while it can be accessed by the application, you can use the System.WeakReference class, you can read more about it <a href="http://msdn.microsoft.com/en-us/library/system.weakreference.aspx" target="_blank">HERE</a>.</p>
<p>P.S. I&#8217;ve test all the examples above under .NET Frawork 3.5.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devtheweb.net/blog/2010/03/04/things-you-probably-didnt-know-about-csharp-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>public static or static public</title>
		<link>http://www.devtheweb.net/blog/2010/02/28/public-static-or-static-public/</link>
		<comments>http://www.devtheweb.net/blog/2010/02/28/public-static-or-static-public/#comments</comments>
		<pubDate>Sun, 28 Feb 2010 11:34:29 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.devtheweb.net/blog/?p=1106</guid>
		<description><![CDATA[Recently, I learned that in PHP and C# declarations like static public or static private are absolutely valid declarations of static methods. You can use both declarations, they has same meaning and there is no recommendation which one should be used: public static function myStaticMethod() or static public function myStaticMethod() But in my practice I [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I learned that in PHP and C# declarations like <em><strong>static public</strong></em> or <em><strong>static private</strong></em> are absolutely valid declarations of static methods.</p>
<p>You can use both declarations, they has same meaning and there is no recommendation which one should be used:</p>
<p>public static function myStaticMethod()</p>
<p>or</p>
<p>static public function myStaticMethod()<br />
<!--adsense--><br />
But in my practice I didn&#8217;t see <em><strong>static public</strong></em> declaration. Also, I simple research shows that most of the programmers prefer to put the visibility first. It is better because shows which method can be used. It seems that the better programming practice is to declare <em><strong>public static</strong></em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devtheweb.net/blog/2010/02/28/public-static-or-static-public/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Things you probably didn&#8217;t know about C#</title>
		<link>http://www.devtheweb.net/blog/2010/02/25/things-you-probably-didnt-know-about-csharp/</link>
		<comments>http://www.devtheweb.net/blog/2010/02/25/things-you-probably-didnt-know-about-csharp/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 08:37:21 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.devtheweb.net/blog/?p=1077</guid>
		<description><![CDATA[I had some free time today, so I decided to learn something new in C#, here’s list of most interesting things that I learned: 1. Instead of using (Font f1 = new Font(&#8220;Arial&#8221;, 10.0f)) { using (Font f2 = new Font(&#8220;Calibri&#8221;, 10.0f)) { //t use f1 and f2 here } } it can be written: [...]]]></description>
			<content:encoded><![CDATA[<p>I had some free time today, so I decided to learn something new in C#, here’s list of most interesting things that I learned:</p>
<p>1. Instead of</p>
<p>using (Font f1 = new Font(&#8220;Arial&#8221;, 10.0f))<br />
{<br />
using (Font f2 = new Font(&#8220;Calibri&#8221;, 10.0f))<br />
{<br />
//t use f1 and f2 here<br />
}</p>
<p>}</p>
<p>it can be written:</p>
<p>using (Font f1 = new Font(&#8220;Arial&#8221;, 10.0f), Font f2 = new Font(&#8220;Calibri&#8221;, 10.0f))<br />
{<br />
//t use f1 and f2 here<br />
}<br />
<!--adsense--><br />
2. Instead of</p>
<p>bool NameExists(string name) {</p>
<p>return name == &#8220;dev&#8221; || name == &#8220;the&#8221; || name == &#8220;web&#8221; ||</p>
<p>name == &#8220;.net&#8221;;</p>
<p>}</p>
<p>it can be written:</p>
<p>bool NameExists(string name){</p>
<p>return new[] { &#8220;dev&#8221;, &#8220;the&#8221;, &#8220;web&#8221;, &#8220;.net&#8221; }.Contains(name);</p>
<p>}</p>
<p>3. You can compare strings ignoring cases in this way str1.ToUpper() == str2.ToUpper(), but it makes additional string allocation, better way is to use OrdinalIgnoreCase: str1.Equals(str2, StringComparison.OrdinalIgnoreCase)</p>
<p>4. The ?? operator can be chained in a bunch of null comparisons:</p>
<p>string result = var1 ?? var2 ?? var3 ?? String.Empty;</p>
<p>5. In the following statement: SomeClass obj = (SomeClass) obj;  If obj is not SomeClass, a class cast exception will be thrown, if you want to return null if obj is not SomeClass, you can use the as operator: SomeClass obj = obj as SameClass;</p>
<p>6. I don’t thinks it’s recommended, but you can use Unicode characters in names, ex.</p>
<p>public string ТихомирIvanov()</p>
<p>{</p>
<p>return &#8220;My name is Tihomir Ivanov&#8221;;</p>
<p>}</p>
<p>But more interesting is that you can also use Unicode escapes, ex.</p>
<p>public string Tu0418хомирIvanov ()</p>
<p>{</p>
<p>return &#8220;My name is Tihomir Ivanov&#8221;;</p>
<p>}</p>
<p>7. In C# you can create JavaScript-like anonymous inline functions, ex.</p>
<p>var var1 = new Func&lt;String&gt;(() =&gt;</p>
<p>{</p>
<p>return &#8220;DevTheWeb.NET&#8221;;</p>
<p>})();</p>
<p>8. Let’s we have the following  generic method declaration:</p>
<p>public void Func&lt;T&gt;(T value);</p>
<p>We can call it in this way: Func&lt;int&gt;(1);</p>
<p>But we can also in this way:</p>
<p>Func(5);<br />
Note: The second way of calling a generic method won’t work if we&#8217;re calling the method through reflection.</p>
<p>That’s all. I hope you’ve found something useful in the examples above. Next Thursday, I’ll add new post about interesting things in C#.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devtheweb.net/blog/2010/02/25/things-you-probably-didnt-know-about-csharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Should you create separate file for new enum in .NET?</title>
		<link>http://www.devtheweb.net/blog/2010/02/20/should-you-create-separate-file-for-new-enum-in-dot-net/</link>
		<comments>http://www.devtheweb.net/blog/2010/02/20/should-you-create-separate-file-for-new-enum-in-dot-net/#comments</comments>
		<pubDate>Sat, 20 Feb 2010 12:15:19 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[best practices]]></category>

		<guid isPermaLink="false">http://www.devtheweb.net/blog/?p=1032</guid>
		<description><![CDATA[You may become in the following situation: You have some class and you want to add some enum for it, then you begin wandering should you add a new file for the enum. I think if the enum will be used by a single class then you should add the enum declaration inside the class. [...]]]></description>
			<content:encoded><![CDATA[<p>You may become in the following situation: You have some class and you want to add some enum for it, then you begin wandering should you add a new file for the enum.</p>
<p>I think if the enum will be used by a single class then you should add the enum declaration inside the class. But if the enum is global and will be used by many classes you can create a new file where you can add declarations of all globally used enums. But to create separate files for all enums it too wasteful <img src='http://www.devtheweb.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.devtheweb.net/blog/2010/02/20/should-you-create-separate-file-for-new-enum-in-dot-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to declare and init a static Dictionary</title>
		<link>http://www.devtheweb.net/blog/2010/02/15/how-to-declare-and-init-a-static-dictionary/</link>
		<comments>http://www.devtheweb.net/blog/2010/02/15/how-to-declare-and-init-a-static-dictionary/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 09:14:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dictionary]]></category>

		<guid isPermaLink="false">http://www.devtheweb.net/blog/?p=986</guid>
		<description><![CDATA[You may want to declare a static Dictionary variable in you code, here&#8217;s a simple example how it can be done in C#: using System.Collections.Generic; &#8230; public static Dictionary&#60;string, string&#62; dict = new Dictionary&#60;string, string&#62;() { {&#8220;key 1&#8243;, &#8220;value 1&#8243;}, {&#8220;key 2&#8243;, &#8220;value 2&#8243;}, {&#8220;key 3&#8243;, &#8220;value 3&#8243;} }; That&#8217;s all. It&#8217;s similar to the [...]]]></description>
			<content:encoded><![CDATA[<p>You may want to declare a static Dictionary variable in you code, here&#8217;s a simple example how it can be done in C#:</p>
<p><span style="color: #0000ff;">using</span> System.Collections.Generic;</p>
<p>&#8230;</p>
<p><span style="color: #0000ff;">public static</span> <span style="color: #33cccc;">Dictionary</span>&lt;<span style="color: #0000ff;">string</span>, <span style="color: #0000ff;">string</span>&gt; dict = <span style="color: #0000ff;">new </span><span style="color: #33cccc;">Dictionary</span>&lt;<span style="color: #0000ff;">string</span>, <span style="color: #0000ff;">string</span>&gt;() {<br />
{<span style="color: #800000;">&#8220;key 1&#8243;</span>, <span style="color: #800000;">&#8220;value 1&#8243;</span>},<br />
{<span style="color: #800000;">&#8220;key 2&#8243;</span>, <span style="color: #800000;">&#8220;value 2&#8243;</span>},<br />
{<span style="color: #800000;">&#8220;key 3&#8243;</span>, <span style="color: #800000;">&#8220;value 3&#8243;</span>}<br />
};</p>
<p>That&#8217;s all. It&#8217;s similar to the array declaration <img src='http://www.devtheweb.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.devtheweb.net/blog/2010/02/15/how-to-declare-and-init-a-static-dictionary/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Tips and Tricks</title>
		<link>http://www.devtheweb.net/blog/2009/10/20/csharp-tips-and-tricks/</link>
		<comments>http://www.devtheweb.net/blog/2009/10/20/csharp-tips-and-tricks/#comments</comments>
		<pubDate>Tue, 20 Oct 2009 12:19:08 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.dev-the-web.com/blog/?p=224</guid>
		<description><![CDATA[1. Convert a string to a Byte[] array: byte[] string2byteArr = System.Text.UnicodeEncoding.GetBytes(&#8220;Some String&#8221;); 2. Lazy load something rather than Foo foo; public Foo Foo { get { if (foo == null) { foo = new Foo(); } return foo; } } you can try: Foo foo; public Foo Foo { get { return foo ?? [...]]]></description>
			<content:encoded><![CDATA[<p><strong>1. Convert a string to a Byte[] array:</strong></p>
<p>byte[] string2byteArr = System.Text.UnicodeEncoding.GetBytes(&#8220;Some String&#8221;);</p>
<p><strong>2. Lazy load something</strong></p>
<p>rather than</p>
<p>Foo foo;<br />
public Foo Foo<br />
{<br />
get<br />
{<br />
if (foo == null)<br />
{<br />
foo = new Foo();<br />
}<br />
return foo;<br />
}<br />
}</p>
<p>you can try:</p>
<p>Foo foo;<br />
public Foo Foo<br />
{<br />
get { return foo ?? (foo = new Foo()); }<br />
}</p>
<p><strong>3. Converting single char to string</strong></p>
<p>char myChar = &#8216;A&#8217;;</p>
<p>rather than</p>
<p>string myString = new string(char [] { mychar });</p>
<p>you can try:</p>
<p>string myString = mychar.toString();</p>
<p><strong>4. String literals can span multiple lines:</strong></p>
<p>string s = @&#8221;First Line<br />
Second Line<br />
Last Line&#8221;;</p>
<p><strong>5. Object initializers</strong><br />
rather than</p>
<p>public class Foo<br />
{<br />
public string Bar { get; set; }<br />
}</p>
<p>for (int i = 0; i &lt; 100; i++)<br />
{<br />
Foo foo = new Foo();<br />
foo.Bar = &#8220;Hello World&#8221;;<br />
myList.Add(foo);<br />
}</p>
<p>instead of</p>
<p>for (int i = 0; i &lt; 100; i++)<br />
myList.Add(new Foo { Bar = &#8220;Hello World&#8221; });</p>
<p><strong>6. Using the &#8216;default&#8217; keyword in generic types:</strong></p>
<p>T t = default(T);</p>
<p>results in a &#8216;null&#8217; if T is a reference type, and 0 if it is an int, false if it is a boolean, etc.</p>
<p><strong>7.  If you want to exit your program without calling any finally blocks or finalizers use:</strong></p>
<p>Environment.FailFast()</p>
<p><strong>8. Compare strings ignoring cases instead of using ToLower method:</strong></p>
<p>&#8220;Some String&#8221;.Equals(&#8220;string STRING&#8221;, StringComparison.InvariantCultureIgnoreCase);</p>
<p><strong>9. Regular expressions and file paths:</strong></p>
<p>&#8220;c:\program files\oldway&#8221;<br />
@&#8221;c:program filenewway&#8221;</p>
<p><strong>10.  Implicit generic parameters on functions:</strong></p>
<p>public void Something&lt;T&gt;(T value);</p>
<p>Instead of</p>
<p>Something&lt;int&gt;(5);</p>
<p>You can:</p>
<p>Something(5);</p>
]]></content:encoded>
			<wfw:commentRss>http://www.devtheweb.net/blog/2009/10/20/csharp-tips-and-tricks/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Top C# Programming Mistakes</title>
		<link>http://www.devtheweb.net/blog/2009/08/27/top-csharp-programming-mistakes/</link>
		<comments>http://www.devtheweb.net/blog/2009/08/27/top-csharp-programming-mistakes/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 18:40:32 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://dev-the-web.com/blog/?p=139</guid>
		<description><![CDATA[1.Using String variables: if (someString.Length &#62; 0) { // &#8230; } &#8230; but someString could be a null: if  (!String.IsNullOrEmpty(someString)) { // much better now !? } 2.String concatenation string s = &#8220;dev&#8221;; s += &#8220;-&#8221;; s += &#8220;the&#8221;; s += &#8220;-&#8221;; s += &#8220;web&#8221;; s += &#8220;.&#8221;; s += &#8220;com&#8221;; This is not very [...]]]></description>
			<content:encoded><![CDATA[<p><strong><a href="http://www.devtheweb.net/blog/wp-content/uploads/2009/08/csharp.jpg" rel="lightbox[139]"><img class="alignnone size-full wp-image-321" title="csharp" src="http://www.devtheweb.net/blog/wp-content/uploads/2009/08/csharp.jpg" alt="" width="100" height="75" /></a></strong></p>
<p><strong>1.Using String variables:</strong></p>
<p>if (someString.Length &gt; 0)<br />
{<br />
// &#8230;<br />
}</p>
<p>&#8230; but someString could be a null:</p>
<p>if  (!String.IsNullOrEmpty(someString))<br />
{<br />
// much better now !?<br />
}</p>
<p><strong>2.String concatenation</strong></p>
<p>string s = &#8220;dev&#8221;;<br />
s += &#8220;-&#8221;;<br />
s += &#8220;the&#8221;;<br />
s += &#8220;-&#8221;;<br />
s += &#8220;web&#8221;;<br />
s += &#8220;.&#8221;;<br />
s += &#8220;com&#8221;;</p>
<p>This is not very effective and the program will work slower instead of using StringBuilder class and it&#8217;s Append method:</p>
<p>StringBuilder sb = new StringBuilder();<br />
sb.Append(&#8220;dev&#8221;);<br />
sb.Append(&#8220;-&#8221;);<br />
sb.Append(&#8220;the&#8221;);<br />
sb.Append(&#8220;-&#8221;);<br />
sb.Append(&#8220;web&#8221;);<br />
sb.Append(&#8220;.&#8221;);<br />
sb.Append(&#8220;com&#8221;);<br />
<strong>3.Using Console</strong></p>
<p>Console.WriteLine(&#8220;A= &#8221; + 1 + &#8221; B=&#8221; + 2 + &#8221; C= &#8221; + someValue);</p>
<p>same as 2. it&#8217;s not very effective. What about this:</p>
<p>Console.WriteLine(&#8220;A: {0}nB: {1}nC: {2}&#8221;, 1, 2, someValue);</p>
<p><strong>4.Parse Integer value from string variable</strong></p>
<p>int i = int.Parse(Request.QueryString["id"]);</p>
<p>but if we&#8217;ve a url like this yourpage.aspx?id=A6 the above method will throw an exception. What about TryParse method?</p>
<p>int i;<br />
if (!int.TryParse(Request.QueryString["id"] , out i))<br />
{<br />
//&#8230;<br />
}</p>
<p><strong>5. Calling IDbConnection&#8217;s Close method</strong></p>
<p>IDbConnection dbConn = null;</p>
<p>try<br />
{<br />
dbConn = new SqlConnection(&#8220;some Connection String&#8221;);<br />
dbConn.Open();<br />
}<br />
finally<br />
{<br />
dbConn.Close();<br />
}</p>
<p>Calling SqlConnection&#8217; constructor may throw an Exception, should we call Close method then !?</p>
<p>IDbConnection dbConn = null;</p>
<p>try<br />
{<br />
dbConn = new SqlConnection(&#8220;Some Connection String&#8221;);<br />
dbConn.Open();<br />
}<br />
finally<br />
{<br />
if (dbConn != null)<br />
{<br />
dbConn.Close();<br />
}<br />
}</p>
<p><strong>6.Using List class</strong></p>
<p>public void SomeMethod(List&lt;SomeItem&gt; items)<br />
{<br />
foreach(var item in items)<br />
{<br />
// do something with the item&#8230;<br />
}<br />
}</p>
<p>If we just loop through the List of items. In this case, requiring a list is an over specification, so it could done in this way:</p>
<p>public void SomeMethod(IEnumerable&lt;SomeItem&gt; items)<br />
{<br />
foreach(var item in items)<br />
{<br />
// do something with the item&#8230;<br />
}<br />
}</p>
<p><strong>7.Use numbers in more that simple numbers way</strong></p>
<p>if(mode == 1) { &#8230; }<br />
else if(mode == 2) { &#8230; }<br />
else if(mode == 3) { &#8230; }</p>
<p>Why don&#8217;t we use Enumerations in this case:</p>
<p>public enum SomeEnumerator<br />
{<br />
DefaultMode = 1,<br />
SafeMode = 2,<br />
NormalMode = 3<br />
}</p>
<p>if(mode == SomeEnumerator.DefaultMode) { &#8230; }<br />
else if(mode == SomeEnumerator.SafeMode) { &#8230; }<br />
else if(mode == SomeEnumerator.NormalMode) { &#8230; }</p>
<p><strong>8.String Replace</strong></p>
<p>string s = &#8220;www.DevTheWeb.NET is a cool site&#8221;;<br />
s.Replace(&#8220;cool&#8221;, &#8220;awful&#8221;);</p>
<p>Nothing changed in s&#8217; value, it&#8217;s still &#8220;www.DevTheWeb.NET is a cool site&#8221; <img src='http://www.devtheweb.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>s = s.Replace(&#8220;cool&#8221;, &#8220;awful&#8221;);</p>
<p>Now s&#8217; value is realy changed.</p>
<p>I hope you&#8217;ll like the list of common C# mistakes <img src='http://www.devtheweb.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>P.S. If you know some cool C# mistake, please, post a comment about it <img src='http://www.devtheweb.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.devtheweb.net/blog/2009/08/27/top-csharp-programming-mistakes/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

