ip: 18.227.209.101 DKs blog - C# examples

DK's Blog

C# examples

Example of console application reading input parameters (arguments)

using System;

public class CommandLine
{
   public static void Main(string[] args)
   {
       // The Length property is used to obtain the length of the array. 
       // Notice that Length is a read-only property:
       Console.WriteLine("Number of command line parameters = {0}", args.Length);
       for(int i = 0; i < args.Length; i++)
       {
           Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
       }
   }
}


 

Example of regular expression in C# match

//using required
using System.Text.RegularExpressions;

//create reqexp
Regex r = new Regex(@"(.*?)\s+(.*?)\s+(.*?)\s+(.*)", RegexOptions.IgnoreCase);

//test string month-day-year(2 digits)
string s = "20-01-11 05:20AM [dir] directoryName"; 

int year,month,day; //find matches and put it in groups 
Match m = r.Match(s); 
year = Convert.ToInt32 ("20" + m.Groups[1].Value.ToString().Substring(6,2)); 
month = Convert.ToInt32 (m.Groups[1].Value.ToString().Substring(0,2)); 
day = Convert.ToInt32 (m.Groups[1].Value.ToString().Substring(3,2));

 

 

Example of hashtable usage, creating, adding searching, listing ...

//create hashtable 
private Hashtable htable = new Hashtable(); 

//adding new object 
htable.Add("key", object); 

//browse through whole collection 
IDictionaryEnumerator enumerator = localDir.GetEnumerator(); 
while (enumerator.MoveNext()) 
{ 
    Console.WriteLine("key: {0}, value: {1}",enumerator.Key.ToString(),enumerator.Value.ToString()); 
} 

//search for key in collection and get object associated with that key
class SomeObject 
{ 
    public string name=""; 
}
 
string key="some search key"; 
SomeObject o; 
if (htable.ContainsKey(key)) 
{ 
    o = (SomeObject)htable[key]; 
    Console.WriteLine("key: {0}, value: {1}", key, o.name)
}

//get collection size
htable.Count;

 


Example of regular expression replace in C#

 

Regex rgx = new Regex(@"\*+"); //pattern
string result = rgx.Replace("This is input string with ****", "+"); //replace

 

 


 

@2016