Posts Tagged ‘C#’

LINQ: Generate File System Hierarchy in XML

March 26th, 2009 Comments off

I happen to come across the need to export file system hirachy into an XML form for further processing, and here is my LINQ statements that does the job. Please note the recursion usage in XDirectoryElement function. Last word you need to ensure you have permission to read the directories, which doesn’t worry me in my case.

Main Function:

private static XElement XDirectoryElement(String root, String filespec)
return /// Create "Directory" element with Path attribute
new XElement("Directory", new XAttribute("Path", root),
new XElement("Files",  /// Add "Files" sub-element
from file in Directory.GetFiles(root, filespec)orderby file
select new XElement("File", Path.GetFileName(file))),
new XElement("Subdirectories", /// Add "Subdirectories" sub-element
from dir in Directory.GetDirectories(root) orderby dir
select XDirectoryElement(dir, filespec)));  /// Do it recursively!

The usage of the function:

String root = @"C:\Program Files\Microsoft Games";
root = Path.Combine(root, @"");
XElement xde = XDirectoryElement(root, "*.*");
String filename = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "SubDir.xml");
Process.Start(filename);  /// Open explorer to view the file.

A trimmed down version of the Output:

< ?xml version="1.0" encoding="utf-8"?>
<directory Path="C:\Program Files\Microsoft Games">
  <files />
    <directory Path="C:\Program Files\Microsoft Games\Chess">
        <directory Path="C:\Program Files\Microsoft Games\Chess\en-US">
          <subdirectories />

Categories: Linq Tags: , ,

C# function parameters passing

March 24th, 2009 Comments off

Yes, C# doesn’t support variable number of parameters in function signature,
by default, according to MSDN, the parameters passed by value:

A parameter declared with no modifiers is a value parameter. A value parameter corresponds to a local variable that gets its initial value from the corresponding argument supplied in the method invocation.

But there is something more interesting than that:

ref keyword: pass the value of the parameter into the function body by reference.

void addme(ref int i){
...... in some function body..
i = 10;
Console.WriteLine(i); /// output 11;

out keyword: sometimes a single retrurn is not enough; why not use the input parameter as return value container? the parameter specifies with out keyword doen’t need to be initialize.
params keyword: A parameter declared with a params modifier is a parameter array. If a formal parameter list includes a parameter array, it must be the last parameter in the list and it must be of a single-dimensional array type. For example, the types string[] and string[][] can be used as the type of a parameter array, but the type string[,] cannot. It is not possible to combine the params modifier with the modifiers ref and out.

using System;
class Test
static void F(params int[] args) {
Console.Write(”Array contains {0} elements:”, args.Length);
foreach (int i in args)
Console.Write(” {0}”, i);
static void Main() {
int[] arr = {1, 2, 3};
F(10, 20, 30, 40);

Output is
Array contains 3 elements: 1 2 3
Array contains 4 elements: 10 20 30 40
Array contains 0 elements:
For details you can refer to MSDN document HERE

Categories: C#, Tech Tags: , ,

C# modifiers for classes (C), methods(M), properties(P), indexers(I), events(E), field(F) and operator(O)

March 22nd, 2009 Comments off

There are quite a few the C# modifiers, depends on the modifiers, they can be used on classes (C), methods(M), properties(P), indexers(I), events(E), field(F) and operator(O) here are the summary (which may be imcompleted). abstract Usage: C M P I E const Usage: P Note: Only can be initialize in declearation field. All const are static! readonly Usage: F NOTE: Assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class. You can only pass the readonly var into a method with ref or out modifier. event Usage: M (delegate) Note: An event must modify a deligate, it acts as a subscription point for other methods with the same signiture of the deligate it modifies. You need to declear a delegate, then associate the event with it. // event_keyword.cs using System; public delegate void MyDelegate(); // delegate declaration extern Usage: M Note: Use the extern modifier in a method declaration to indicate that the method is implemented externally. A common use of the extern modifier is with the DllImport attribute. (Similar to C/C++ external link)

public interface I {  
event MyDelegate MyEvent;  
void FireAway(); 
public class MyClass: I {
  public event MyDelegate MyEvent;
  public void FireAway(){
   if (MyEvent != null)

public class MainClass {
  static private void f()  {
   Console.WriteLine{"This is called when the event fires.");  
  static public void Main ()  {
   I i = new MyClass();
   i.MyEvent += new MyDelegate(f);

override Usage: M P I E Note: The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method. You cannot override a non-virtual or static method. Both the override method and the virtual method must have the same access level modifier. new Usage: M P F Note: use it to hide the parent class’s member. sealed Usage: C M P Note:A sealed class cannot be inherited. It is an error to use a sealed class as a base class. Use the sealed modifier in a class declaration to prevent inheritance of the class. Structs are implicitly sealed; therefore, they cannot be inherited. static Usage: F M P O E constructor Note: A constant or type declaration is implicitly a static member. F/M/P/O/E: class level static, must access from class level Class.method or Class.field Constructor: Static constructor is a special method which gets called when the class assembly get loaded, and NO extra modifier for static constructor unsafe Usage: M Note: The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers. virtual Usgae: M P Note:By default, methods are non-virtual. Virtual enables dynamic binding. volatile Usage: F Note: It indicates modified Object can be chaanged unexpectedly. The type of a field marked as volatile is restricted to the following types: Any reference type. Any pointer type (in an unsafe context). The types sbyte, byte, short, ushort, int, uint, char, float, bool. An enum type with an enum base type of byte, sbyte, short, ushort, int, or uint. unchecked Usage: Block Note: The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.

unchecked {
  int val = 2147483647 * 2; 
public int UncheckedAdd(int a, int b) {
  return unchecked(a + b); 
Categories: C#, Tech Tags: , , ,