tags:

views:

101

answers:

0

Possible Duplicate:
Hidden Features of C#?

Hello Everyone,

I'm just wondering what little C# tricks that programmers use in their day-to-day work.

I have two - One, an overlooked, for me, language feature. The other a solution to an often occuring need.

1 - Returning a default value (often from collections like ViewState or Session)

How often do you write code like this?

if(Session["VariableName"] != null && ....

or

if(String.IsNullOrEmpty(Session["VariableName"]) ...

To retrieve the value.

Well, Resharper slapped me on the hand the first time I tried that after I had installed it. It said to use this instead:

var MyVariable = Session["VariableName"] ?? string.empty

Soooo much easier.

2 - Counting the number of sub-strings in a string (Without looping in my code).

string myString = "Lorem ipsum dolor sit amet, " +   
"consectetur adipisicing elit, sed do eiusmod " + 
"tempor incididunt ut labore et dolore magna " + 
"aliqua. Ut enim ad minim veniam, quis nostrud " +
"exercitation ullamco laboris nisi ut aliquip " +    
"ex ea commodo consequat. Duis aute irure " + 
"dolor in reprehenderit in voluptate velit " +    
"esse cillum dolore eu fugiat nulla pariatur. " +    
"Excepteur sint occaecat cupidatat non proident, " +    
"sunt in culpa qui officia deserunt mollit anim " +    
"id est laborum.";

string mySubString = "dolor";
int Count = (myString.Length - myString.Replace(mySubString, string.Empty).Length) / mySubString.Length;