Nano's Blog

03/08/2010

Typeof() and GetType() in C#

Filed under: programming — Tags: — nano @ 02:05
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace testNameSpace
{

    class testClass
    {
        public static void Main()
        {
            System.Type type0 = typeof(int);
            Console.WriteLine("{0}", type0);

            int i = 0;
            System.Type type1 = i.GetType();
            Console.WriteLine("{0}", type1);

        }
    }
}

output

System.Int32
System.Int32

More:
MSDN : http://msdn.microsoft.com/en-us/library/58918ffs(VS.80).aspx

01/04/2010

How to print a complex dictionary with StringBuilder?

Filed under: programming — Tags: , — nano @ 10:14

Purpose

Create a complex dictionary
Print the dictionary with StringBuilder

Scope

C#, Dictionary, StringBuilder

Limitations

The sample dictionary was fixed. The code can’t handle the dynamical dictionary.

Note
1.

// watch out for NullReferenceException
            if (!ReferenceEquals(null, mainDict[pair1.Key]) && (mainDict[pair1.Key] is string))

2.

// IDictionary is not the one from the Generics namespace, it is the one from the System.Collections namespace
using System.Collections;

Code Sample

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

class test
{
    private static Dictionary<string, object> mainDict = new Dictionary<string, object>();

    public static void Main()
    {
        Dictionary<string, object> aSubDict = new Dictionary<string,object>();
        Dictionary<string, object> aSub1Dict = new Dictionary<string, object>();
        Dictionary<string, object> aSub2Dict = new Dictionary<string, object>();
        Dictionary<string, object> aSub3Dict = new Dictionary<string, object>();
        Dictionary<string, object> aSub4Dict = new Dictionary<string, object>();

        mainDict.Add("ADKey", aSubDict);
        mainDict.Add("ASKey", "AValue");
        aSubDict.Add("BDKey", aSub1Dict);
        aSubDict.Add("BSKey", "BValue");
        aSub1Dict.Add("CDKey", aSub2Dict);
        aSub1Dict.Add("CSKey", "CValue");
        aSub2Dict.Add("DDKey",aSub3Dict);
        aSub2Dict.Add("DSKey", "DValue");
        aSub3Dict.Add("EDKey", aSub4Dict);
        aSub3Dict.Add("ESKey", "EValue");
        aSub4Dict.Add("FKey", "FValue");

        StringBuilder sb;

        foreach (KeyValuePair<string, object> pair1 in mainDict)
            // watch out for NullReferenceException
            if (!ReferenceEquals(null, mainDict[pair1.Key]) && (mainDict[pair1.Key] is string))
            {
                Console.WriteLine("Key = {0}, Value = {1}", pair1.Key, pair1.Value);
                sb = new StringBuilder();
                sb.AppendFormat("{0}, {1}", pair1.Key, pair1.Value);
                Console.WriteLine(sb.ToString());
            }
            // IDictionary is not the one from the Generics namespace, it is the one from the System.Collections namespace
            else if (!ReferenceEquals(null, mainDict[pair1.Key]) && (mainDict[pair1.Key] is Dictionary<string, object>))
            {
                foreach (KeyValuePair<string, object> pair2 in (Dictionary<string, object>)pair1.Value)
                    if (!ReferenceEquals(null, ((Dictionary<string, object>)pair1.Value)[pair2.Key]) && (((Dictionary<string, object>)pair1.Value)[pair2.Key] is string))
                    {
                        Console.WriteLine("SubKey = {0}, Value = {1}", pair2.Key, pair2.Value);
                        sb = new StringBuilder();
                        sb.AppendFormat("{0}/{1}, {2}", pair1.Key, pair2.Key, pair2.Value);
                        Console.WriteLine(sb.ToString());
                    }
                    else if (!ReferenceEquals(null, ((Dictionary<string, object>)pair1.Value)[pair2.Key]) && (((Dictionary<string, object>)pair1.Value)[pair2.Key] is Dictionary<string, object>))
                    {
                        foreach (KeyValuePair<string, object> pair3 in (Dictionary<string, object>)pair2.Value)
                            if (!ReferenceEquals(null, ((Dictionary<string, object>)pair2.Value)[pair3.Key]) && (((Dictionary<string, object>)pair2.Value)[pair3.Key] is string))
                            {
                                Console.WriteLine("SubKey = {0}, Value = {1}", pair3.Key, pair3.Value);
                                sb = new StringBuilder();
                                sb.AppendFormat("{0}/{1}/{2}, {3}", pair1.Key, pair2.Key, pair3.Key, pair3.Value);
                                Console.WriteLine(sb.ToString());
                            }
                            else if (!ReferenceEquals(null, ((Dictionary<string, object>)pair2.Value)[pair3.Key]) && (((Dictionary<string, object>)pair2.Value)[pair3.Key] is Dictionary<string, object>))
                            {
                                foreach (KeyValuePair<string, object> pair4 in (Dictionary<string, object>)pair3.Value)
                                    if (!ReferenceEquals(null, ((Dictionary<string, object>)pair3.Value)[pair4.Key]) && (((Dictionary<string, object>)pair3.Value)[pair4.Key] is string))
                                    {
                                        Console.WriteLine("SubKey = {0}, Value = {1}", pair4.Key, pair4.Value);
                                        sb = new StringBuilder();
                                        sb.AppendFormat("{0}/{1}/{2}/{3}, {4}", pair1.Key, pair2.Key, pair3.Key, pair4.Key, pair4.Value);
                                        Console.WriteLine(sb.ToString());
                                    }
                                    else if (!ReferenceEquals(null, ((Dictionary<string, object>)pair3.Value)[pair4.Key]) && (((Dictionary<string, object>)pair3.Value)[pair4.Key] is Dictionary<string, object>))
                                    {
                                        foreach (KeyValuePair<string, object> pair5 in (Dictionary<string, object>)pair4.Value)
                                            if (!ReferenceEquals(null, ((Dictionary<string, object>)pair4.Value)[pair5.Key]) && (((Dictionary<string, object>)pair4.Value)[pair5.Key] is string))
                                            {
                                                Console.WriteLine("SubKey = {0}, Value = {1}", pair5.Key, pair5.Value);
                                                sb = new StringBuilder();
                                                sb.AppendFormat("{0}/{1}/{2}/{3}/{4}, {5}", pair1.Key, pair2.Key, pair3.Key, pair4.Key, pair5.Key, pair5.Value);
                                                Console.WriteLine(sb.ToString());
                                            }
                                            else if (!ReferenceEquals(null, ((Dictionary<string, object>)pair4.Value)[pair5.Key]) && (((Dictionary<string, object>)pair4.Value)[pair5.Key] is Dictionary<string, object>))
                                            {
                                                foreach (KeyValuePair<string, object> pair6 in (Dictionary<string, object>)pair5.Value)
                                                    if (!ReferenceEquals(null, ((Dictionary<string, object>)pair5.Value)[pair6.Key]) && (((Dictionary<string, object>)pair5.Value)[pair6.Key] is string))
                                                    {
                                                        Console.WriteLine("SubKey = {0}, Value = {1}", pair6.Key, pair6.Value);
                                                        sb = new StringBuilder();
                                                        sb.AppendFormat("{0}/{1}/{2}/{3}/{4}/{5}, {6}", pair1.Key, pair2.Key, pair3.Key, pair4.Key, pair5.Key, pair6.Key, pair6.Value);
                                                        Console.WriteLine(sb.ToString());
                                                    }
                                                    else if (!ReferenceEquals(null, ((Dictionary<string, object>)pair5.Value)[pair6.Key]) && (((Dictionary<string, object>)pair5.Value)[pair6.Key] is Dictionary<string, object>))
                                                    {
                                                        Console.WriteLine("sub Dict Found");
                                                    }
                                            }
                                    }
                            }
                    }
            }
    }
}

Output

SubKey = FKey, Value = FValue
ADKey/BDKey/CDKey/DDKey/EDKey/FKey, FValue
SubKey = ESKey, Value = EValue
ADKey/BDKey/CDKey/DDKey/ESKey, EValue
SubKey = DSKey, Value = DValue
ADKey/BDKey/CDKey/DSKey, DValue
SubKey = CSKey, Value = CValue
ADKey/BDKey/CSKey, CValue
SubKey = BSKey, Value = BValue
ADKey/BSKey, BValue
Key = ASKey, Value = AValue
ASKey, AValue

Requirement
Code above tested in Visual Studio 2005 Professional Edition compiled against FrameWork 2.0 SP2.

- from StackOverflow.com

01/02/2010

how to implement a collection class that can be used with the foreach statement

Filed under: programming — Tags: , — nano @ 15:40

The foreach statement is a convenient way to iterate over the elements of an array. It can also enumerate the elements of a collection, provided that the collection class has implemented the System.Collections.IEnumerator and System.Collections.IEnumerable interfaces.

Example1.

The following code sample illustrates how to write a collection class that can be used with foreach. The class is a string tokenizer, similar to the C run-time function strtok.

Notice that, internally, Tokens uses an array, which implements IEnumerator and IEnumerable itself. The code sample could have leveraged the array’s enumeration methods as its own, but that would have defeated the purpose of this example.

In C#, it is not strictly necessary for a collection class to inherit from IEnumerable and IEnumerator in order to be compatible with foreach; as long as the class has the required GetEnumerator, MoveNext, Reset, and Current members, it will work with foreach. Omitting the interfaces has the advantage of allowing you to define the return type of Current to be more specific than object, thereby providing type-safety.

// tokens.cs
using System;
// The System.Collections namespace is made available:
using System.Collections;

// Declare the Tokens class:
public class Tokens : IEnumerable
{
    private string[] elements;

    Tokens(string source, char[] delimiters)
    {
        // Parse the string into tokens:
        elements = source.Split(delimiters);
    }

    // IEnumerable Interface Implementation:
    //   Declaration of the GetEnumerator() method
    //   required by IEnumerable
    public IEnumerator GetEnumerator()
    {
        return new TokenEnumerator(this);
    }

    // Inner class implements IEnumerator interface:
    private class TokenEnumerator : IEnumerator
    {
        private int position = -1;
        private Tokens t;

        public TokenEnumerator(Tokens t)
        {
            this.t = t;
        }

        // Declare the MoveNext method required by IEnumerator:
        public bool MoveNext()
        {
            if (position < t.elements.Length - 1)
            {
                position++;
                return true;
            }
            else
            {
                return false;
            }
        }

        // Declare the Reset method required by IEnumerator:
        public void Reset()
        {
            position = -1;
        }

        // Declare the Current property required by IEnumerator:
        public object Current
        {
            get
            {
                return t.elements[position];
            }
        }

    }

    // Test Tokens, TokenEnumerator

    static void Main()
    {
        // Testing Tokens by breaking the string into tokens:
        // the following code is used to Tokens by breaking "This is a well-done program." into tokens (using ' ' and '-' as separators) and enumerating those tokens with the foreach statement:
        Tokens f = new Tokens("This is a well-done program.",
           new char[] { ' ', '-' });
        foreach (string item in f)
        {
            Console.WriteLine(item);
        }
    }
}

Example2.

This sample is equivalent in function to Example 1, but it provides additional type-safety in C# while maintaining interoperability with other languages.


// tokens2.cs
using System;
using System.Collections;

public class Tokens : IEnumerable
{
    private string[] elements;

    Tokens(string source, char[] delimiters)
    {
        elements = source.Split(delimiters);
    }

    // IEnumerable Interface Implementation:

    public TokenEnumerator GetEnumerator() // non-IEnumerable version
    {
        return new TokenEnumerator(this);
    }

    IEnumerator IEnumerable.GetEnumerator() // IEnumerable version
    {
        return (IEnumerator)new TokenEnumerator(this);
    }

    // Inner class implements IEnumerator interface:

    public class TokenEnumerator : IEnumerator
    {
        private int position = -1;
        private Tokens t;

        public TokenEnumerator(Tokens t)
        {
            this.t = t;
        }

        public bool MoveNext()
        {
            if (position < t.elements.Length - 1)
            {
                position++;
                return true;
            }
            else
            {
                return false;
            }
        }

        public void Reset()
        {
            position = -1;
        }

        public string Current // non-IEnumerator version: type-safe
        {
            get
            {
                return t.elements[position];
            }
        }

        object IEnumerator.Current // IEnumerator version: returns object
        {
            get
            {
                return t.elements[position];
            }
        }
    }

    // Test Tokens, TokenEnumerator

    static void Main()
    {
        Tokens f = new Tokens("This is a well-done program.",
           new char[] { ' ', '-' });
        foreach (string item in f) // try changing string to int
        {
            Console.WriteLine(item);
        }
    }
}

example1 and example2 Output :

This
is
a
well
done
program.

- from msdn.com

versioning in C# through the use of the override and new keywords

Filed under: programming — Tags: , — nano @ 15:10

The C# language is designed such that versioning between base and derived classes in different libraries can evolve and maintain backwards compatibility. This means, for example, that the introduction of a new member in a base class with the same name as a member in a derived class is not an error. It also means that a class must explicitly state whether a method is intended to override an inherited method, or whether a method is a new method that simply hides a similarly named inherited method.

In C#, methods are by default, not virtual. To make a method virtual, the virtual modifier has to be used in the method declaration of the base class. The derived class can then override the base virtual method by using the override keyword or hide the virtual method in the base class by using the new keyword. If neither the override keyword nor the new keyword is specified, the compiler will issue a warning and the method in the derived class will hide the method in the base class. The following example shows these concepts in action.

// versioning.cs
// CS0114 expected
public class MyBase
{
    public virtual string Meth1()
    {
        return "MyBase-Meth1";
    }
    public virtual string Meth2()
    {
        return "MyBase-Meth2";
    }
    public virtual string Meth3()
    {
        return "MyBase-Meth3";
    }
}

class MyDerived : MyBase
{
    // Overrides the virtual method Meth1 using the override keyword:
    public override string Meth1()
    {
        return "MyDerived-Meth1";
    }
    // Explicitly hide the virtual method Meth2 using the new
    // keyword:
    public new string Meth2()
    {
        return "MyDerived-Meth2";
    }
    // Because no keyword is specified in the following declaration
    // a warning will be issued to alert the programmer that
    // the method hides the inherited member MyBase.Meth3():
    // warning CS0114: 'MyDerived.Meth3()' hides inherited member 'MyBase.Meth3()'.
    // To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
    public string Meth3()
    {
        return "MyDerived-Meth3";
    }

    public static void Main()
    {
        MyDerived mD = new MyDerived();
        MyBase mB = (MyBase)mD;

        System.Console.WriteLine(mB.Meth1());
        System.Console.WriteLine(mB.Meth2());
        System.Console.WriteLine(mB.Meth3());
    }
}

Output

MyDerived-Meth1
MyBase-Meth2
MyBase-Meth3

- from msdn.com

how properties are an integral part of the C# programming language – Part 2

Filed under: programming — Tags: , — nano @ 13:40

The following example shows how to define abstract properties. An abstract property declaration does not provide an implementation of the property accessors. The example demonstrates how to override these properties in subclasses.

This sample consists of three files. In the Properties Sample, these files are compiled into a single compilation but in this tutorial, each file is compiled individually and its resulting assembly referenced by the next compilation:


// compile with: /target:library
// csc /target:library abstractshape.cs
using System;

// abstractshape.cs The Shape class that contains an abstract Area property
public abstract class Shape
{
    private string myId;

    public Shape(string s)
    {
        Id = s;   // calling the set accessor of the Id property
    }

    public string Id
    {
        get
        {
            return myId;
        }

        set
        {
            myId = value;
        }
    }

    // Area is a read-only property - only a get accessor is needed:
    public abstract double Area
    {
        get;
    }

    public override string ToString()
    {
        return Id + " Area = " + string.Format("{0:F2}", Area);
    }
}

// shapes.cs The subclasses of the Shape class.
// compile with: /target:library /reference:abstractshape.dll
// shows three subclasses of Shape and how they override the Area property to provide their own implementation.
public class Square : Shape
{
    private int mySide;

    public Square(int side, string id)
        : base(id)
    {
        mySide = side;
    }

    public override double Area
    {
        get
        {
            // Given the side, return the area of a square:
            return mySide * mySide;
        }
    }
}

public class Circle : Shape
{
    private int myRadius;

    public Circle(int radius, string id)
        : base(id)
    {
        myRadius = radius;
    }

    public override double Area
    {
        get
        {
            // Given the radius, return the area of a circle:
            return myRadius * myRadius * System.Math.PI;
        }
    }
}

public class Rectangle : Shape
{
    private int myWidth;
    private int myHeight;

    public Rectangle(int width, int height, string id)
        : base(id)
    {
        myWidth = width;
        myHeight = height;
    }

    public override double Area
    {
        get
        {
            // Given the width and height, return the area of a rectangle:
            return myWidth * myHeight;
        }
    }
}

// shapetest.cs test program to display the areas of some Shape-derived objects.
// compile with: /reference:abstractshape.dll;shapes.dll
// The following code shows a test program that creates a number of Shape-derived objects and prints out their areas.
public class TestClass
{
    public static void Main()
    {
        Shape[] shapes =
         {
            new Square(5, "Square #1"),
            new Circle(3, "Circle #1"),
            new Rectangle( 4, 5, "Rectangle #1")
         };

        System.Console.WriteLine("Shapes Collection");
        foreach (Shape s in shapes)
        {
            System.Console.WriteLine(s);
        }

    }
}

- from msdn.com

how properties are an integral part of the C# programming language – Part 1

Filed under: programming — Tags: , — nano @ 10:46

a Person class that has two properties: Name (string) and Age (int). Both properties are read/write.

// person.cs
using System;
class Person
{
    private string myName = "N/A";
    private int myAge = 0;

    // Declare a Name property of type string:
    public string Name
    {
        get
        {
            return myName;
        }
        set
        {
            // Note that in a property Set method a special value variable is available.
            // This variable contains the value that the user specified
            myName = value;
        }
    }

    // Declare an Age property of type int:
    public int Age
    {
        get
        {
            return myAge;
        }
        set
        {
            myAge = value;
        }
    }

    public override string ToString()
    {
        return "Name = " + Name + ", Age = " + Age;
    }

    public static void Main()
    {
        Console.WriteLine("Simple Properties");

        // Create a new Person object:
        Person person = new Person();

        // Name() and Age() called by the WriteLine()
        // Print out the name and the age associated with the person:
        // Notice that ToString is not explicitly used in the program.
        // It is invoked by default by the WriteLine calls.
        Console.WriteLine("Person details - {0}", person);

        // Set some values on the person object:
        person.Name = "Joe";
        person.Age = 99;
        Console.WriteLine("Person details - {0}", person);

        // Increment the Age property:
        // Notice the clean syntax for incrementing the Age property on a Person object:
        // the equivalent code might look like this: person.SetAge(person.GetAge() + 1);
        person.Age += 1;
        Console.WriteLine("Person details - {0}", person);
    }
}

Output:

Simple Properties
Person details - Name = N/A, Age = 0
Person details - Name = Joe, Age = 99
Person details - Name = Joe, Age = 100

- from msdn.com

Arrays in General

Filed under: programming — Tags: , , — nano @ 06:39

C# arrays are zero indexed; that is, the array indexes start at zero. Arrays in C# work similarly to how arrays work in most other popular languages There are, however, a few differences that you should be aware of.

When declaring an array, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.

// arrays.cs
using System;
class DeclareArraysSample
{
    public static void Main()
    {
        // Single-dimensional array
        int[] numbers = new int[5];

        // Multidimensional array
        string[,] names = new string[5,4];

        // Array-of-arrays (jagged array)
        byte[][] scores = new byte[5][];

        // Create the jagged array
        for (int i = 0; i < scores.Length; i++)
        {
            scores[i] = new byte[i+3];
        }

        // Print length of each row
        for (int i = 0; i < scores.Length; i++)
        {
            Console.WriteLine("Length of row {0} is {1}", i, scores[i].Length);
        }
    }
}

Output

Length of row 0 is 3
Length of row 1 is 4
Length of row 2 is 5
Length of row 3 is 6
Length of row 4 is 7

Using foreach on Arrays

using System;
class DeclareArraysSample
{
    public static void Main()
    {
        int[,] numbers = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
        foreach (int i in numbers)
        {
            Console.Write("{0} ", i);
        }
    }
}

Output

9 99 3 33 5 55

- from msdn.com

Command Line Arguments

Filed under: programming — Tags: , — nano @ 06:16
// arguments: A B C D
using System;

public class Hello3
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello, World!");
        Console.WriteLine("You entered the following {0} command line arguments:",
           args.Length);
        for (int i = 0; i < args.Length; i++)
        {
            Console.WriteLine("{0}", args[i]);
        }
    }
}

Input A B C D at the field text area of csporj file properties -> Debug -> Command line agurment

- from msdn.com

Hello World – C#

Filed under: programming — Tags: — nano @ 01:49

using System;
using System.Collections.Generic;
using System.Text;

namespace BlogHelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            // a first script to post at my blog
            // test the syntax highlight plugin
            Console.WriteLine("Hello World.");
            // pause console window
            Console.ReadLine();
        }
    }
}

Powered by WordPress