April 28, 2016

C# Tips



String.Equals(stringA, stringB, StringComparison.CurrentCultureIgnoreCase)

Vs
string pageTitle = suppliedTitle ?? "Default Title"

-----------------------------------------------------------------------------------------------------
MyClass myObject = (MyClass) obj; throw a class InvalidCastException exception. 
Vs
MyClass myObject = obj as MyClass; The second will return null if obj isn't a MyClass

-----------------------------------------------------------------------------------------------------
Employee emp = new Employee {Name="John Smith", StartDate=DateTime.Now()}  
Vs
Employee emp = new Employee();  
emp.Name = "John Smith";  
emp.StartDate = DateTime.Now(); 


-----------------------------------------------------------------------------------------------------

class ExtensionMethods2  
{  
   static void Main()  
   {  
      int[] ints = { 10, 45, 15, 39, 21, 26 };  
      var result = ints.OrderBy(g => g);  
      foreach (var i in result)  
      {  
         System.Console.Write(i + " ");  
      }  
   }  
}  
  
//Output: 10 15 21 26 39 45  

-----------------------------------------------------------------------------------------------------
if(dictionary.ContainsKey(key))  
{  
   value = dictionary[key];  
}  


if(dictionary.TryGetValue(key, out value))  

{ ... } 
-----------------------------------------------------------------------------------------------------

No comments: