Monday, September 15, 2008

C# Crap That Are New to Me ... and Maybe to You Too

I have been involved in software engineering for a while and have been using C# pretty much since it came out in .NET Framework. But every now and then, I encountered something that I have never seen before. This is my attempt to catalog them and share them.

I found some of these just by luck, some from books, some from my colleagues, some from the web sample codes, some from forums, etc etc. So, not everything in my list will be new for you ... but at least they were for (until 5 minutes ago).

If you have anything you want to add, post them in the comments and I will add them in the post with credits to you.

1. ?? (coalescing) operator
"??" (coalescing) operator is simplifying "?" (if-and-only-if) operator, but only for null checking. In "?" operator, you do this (with null):

string result = (x == null ? "no result" : x.ToString());
Now with "??" operator you can simply do this:
string result = x ?? "no result";

2. @ for string
Usually when you have a string assigned with some values, you will have to pay attention to escape characters, etc. With "@", you can literally use string as literals. See this example:
string result = @"c:\windows\my files\";
This line of code will actually produce the expected result "c:\windows\my files\". Without the "@", you will to write something like this:
string result = "c:\\windows\\my files\\";

3. @ for variable names that are also keywords
If you put "@" in front of your local variable, you can name it anything you want, including using keyword-like name, check this out:
string @string = "hello world";

4. C# property constructor initialization
So instead of doing this:
Person objPerson = new Person();
objPerson.Name = "Bob";
objPerson.Phone = "1-(800)-555-5555";
You can do this:
Person objPerson = new Person {Name = "Bob", Phone = "1-(800)-555-5555" };

5. yield
Look here for MSDN explanation.

No comments: