Wednesday, March 26, 2014

Force Explicit Calling of Static Class-Static constructor

The static constructor loads or called only once when any method of static class is invoked or initialize. There is no need of explicit calling of static constructor. But when there is no static property or method to do so then we can have explicit option to call static constructor as given below
typeof(StaticClassName).TypeInitializer.Invoke(null, null);

Monday, March 24, 2014

C# Cool Code Tips

1.Specialized Collection- NameValueCollection
Real time example
Parse a string such as "p1=6&p2=7&p3=8" into a NameValueCollection

NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);

Results-
qscoll["p1"] , qscoll["p2"] and qscoll["p3"]                

Speciality- This NameValueCollection can hold duplicates Key with different Values.

   // Creates and initializes a new NameValueCollection.
      NameValueCollection myCol = new NameValueCollection();
      myCol.Add( "red", "rojo" );
      myCol.Add( "green", "verde" );
      myCol.Add( "blue", "azul" );
      myCol.Add( "red", "rouge" );


 public static void PrintKeysAndValues2( NameValueCollection myCol )  {
      Console.WriteLine( " [INDEX] KEY VALUE" );
      for ( int i = 0; i < myCol.Count; i++ )
         Console.WriteLine( " [{0}] {1,-10} {2}", i, myCol.GetKey(i), myCol.Get(i) );
      Console.WriteLine();
   }

Displays the elements using
GetKey and Get:   
[INDEX] KEY VALUE   
[0]     red rojo,rouge   
[1]     green verde   
[2]     blue azul

2. Array.ConvertAll
Real Time Example
You have string  with comma separated with integer value and you want to have int[] conversion from string [] array.

look at this now!

string commaSep= "1,2,3"
int[] transform= Array.ConvertAll(commaSep.split(','),s=>int.parse(s))

3. Fetch Calling Method Name using CallerMemberNameAttribute C#4.5

In .Net 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute
public class SomeClass
{
    public void SomeMethod([CallerMemberName]string memberName = "")
    {
        Console.WriteLine(memberName); //output will be name of calling method
    }
}


https://stackoverflow.com/questions/3095696/how-do-i-get-the-calling-method-name-and-type-using-reflection

Thursday, March 13, 2014

Linq to replace Dictionary values with XML formed tag values.

static void Main(string[] args)
{
 
IDictionary<string, string> placeHolder = new Dictionary<string, string>();

placeHolder.Add("#FirstName#","Phil");

placeHolder.Add("#MiddleName#", "J");

placeHolder.Add("#LastName#", "Haack");
        string parsedXmlString=GetParsedTemplate(@"



#FirstName#

#MiddleName#

#LastName#





", placeHolder);}
 
 
 

public static string GetParsedTemplate(string wellFormedXML, IDictionary<string, string> placeHolder)
{

placeHolder.AsEnumerable().ToList().ForEach(t => wellFormedXML = wellFormedXML.Replace(t.Key, t.Value));

return wellFormedXML;


}