C# Tips and Tricks

Date: 20 Oct 2009 Comments: 1

1. Convert a string to a Byte[] array:

byte[] string2byteArr = System.Text.UnicodeEncoding.GetBytes(“Some String”);

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 ?? (foo = new Foo()); }
}

3. Converting single char to string

char myChar = ‘A’;

rather than

string myString = new string(char [] { mychar });

you can try:

string myString = mychar.toString();

4. String literals can span multiple lines:

string s = @”First Line
Second Line
Last Line”;

5. Object initializers
rather than

public class Foo
{
public string Bar { get; set; }
}

for (int i = 0; i < 100; i++)
{
Foo foo = new Foo();
foo.Bar = “Hello World”;
myList.Add(foo);
}

instead of

for (int i = 0; i < 100; i++)
myList.Add(new Foo { Bar = “Hello World” });

6. Using the ‘default’ keyword in generic types:

T t = default(T);

results in a ‘null’ if T is a reference type, and 0 if it is an int, false if it is a boolean, etc.

7.  If you want to exit your program without calling any finally blocks or finalizers use:

Environment.FailFast()

8. Compare strings ignoring cases instead of using ToLower method:

“Some String”.Equals(“string STRING”, StringComparison.InvariantCultureIgnoreCase);

9. Regular expressions and file paths:

“c:\\program files\\oldway”
@”c:\program file\newway”

10.  Implicit generic parameters on functions:

public void Something<T>(T value);

Instead of

Something<int>(5);

You can:

Something(5);

  1. One Comments to “C# Tips and Tricks”

    1. C# Tips and Tricks…

      C# Tips and Tricks…

    Leave a Reply


    Spam protection by WP Captcha-Free