Thursday, November 29, 2007

Enumeration

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


class 
Program
{
    
//Flag enums are designed to support bitwise operations on the enum values
    
[Flags]
    
public enum LogLevels : uint
    
{
        
//Increment by powers of 2.
        //If you don't assign explicit values VS increments by 1. 
        
None        0,
        NotifyTrace 
1,
        NotifyDebug 
2,
        NotifyInfo  
4,
        NotifyWarn  
8,
        NotifyError 
16,
        NotifyAll   
=   NotifyTrace | NotifyDebug | NotifyInfo | NotifyWarn | NotifyError,
        
//The rationale for avoiding zero in a flag enumeration for an actual flag 
        //is that you can't OR it in with other flags as expected.
        
NotifyNone  ~(NotifyTrace | NotifyDebug | NotifyInfo | NotifyWarn | NotifyError),
    }

    LogLevels options 
LogLevels.NotifyDebug | LogLevels.NotifyWarn | LogLevels.NotifyError;

    static void 
Main(string[] args)
    {
        Program p 
= new Program();
        
p.Test1();
        
p.Test2();
        
LogLevels v (LogLevels) 2;
        
p.Test3(v);

        
// Interesting, Compiler Catch Invalid Argument
        
p.Test4(2);
        
// Surprise, Correct
        
p.Test4(0);

        
Console.ReadLine();
    
}

    
public void Test1()
    {
        Type 
value = typeof(LogLevels);
        foreach 
(string in Enum.GetNames(value))
        {
            Console.WriteLine(
"{0,-11} = {1}", s, Enum.Format(value, Enum.Parse(value, s), "d"));
        
}
    }

    
public void Test2()
    {
        Console.WriteLine(IsLevelsSet(LogLevels.NotifyNone))
;
        
Console.WriteLine(IsLevelsSet(LogLevels.NotifyTrace));
        
Console.WriteLine(IsLevelsSet(LogLevels.NotifyDebug));
        
Console.WriteLine(IsLevelsSet(LogLevels.NotifyInfo));
        
Console.WriteLine(IsLevelsSet(LogLevels.NotifyWarn));
        
Console.WriteLine(IsLevelsSet(LogLevels.NotifyError));
        
Console.WriteLine(IsLevelsSet(LogLevels.NotifyAll));
    
}

   
    
public void Test3(LogLevels value)
    {
        
switch (value)
        {
            
case LogLevels.NotifyTrace:
                Console.WriteLine(
value.ToString());
                break;
            case 
LogLevels.NotifyDebug:
                Console.WriteLine(
value.ToString());
                break;
            case 
LogLevels.NotifyInfo:
                Console.WriteLine(
value.ToString());
                break;
            case 
LogLevels.NotifyWarn:
                Console.WriteLine(
value.ToString());
                break;
            case 
LogLevels.NotifyError:
                Console.WriteLine(
value.ToString());
                break;
            case 
LogLevels.NotifyAll:
                Console.WriteLine(
value.ToString());
                break;
            case 
LogLevels.NotifyNone:
                Console.WriteLine(
value.ToString());
                break;
            default
:
                
break;
        
}
    }

    
public void Test4(LogLevels value)
    {
        //in C# the literal constant 0 implicitly converts to any enum type             
        
if (value == LogLevels.None)
            Console.WriteLine(
value.ToString());
    
}

    
private bool IsLevelsSet(LogLevels values)
    {
        
return (options & values) == values;
    
}

}

Friday, November 23, 2007

Create Objects From Their Names

//you can use the Activator.Create instance to do so.

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

namespace 
Labs1
{
    
class Program
    {
        
static void Main(string[] args)
        {

            
string TypeName "DerivedTest";
            string 
NmSpace  "Labs2";

            
//gets the System.Type of the control name (must be fully qualified)
            
Type t Type.GetType(NmSpace + "." + TypeName);

            
//Uses the 'Activator' to create a new instance of the specified type
            
Labs2.Test obj1 (Labs2.Test)Activator.CreateInstance(t);

            
//Now, "DerivedTest" is an instance of that type
            
obj1.Method();


            
NmSpace  "Labs3";

            
Type.GetType(NmSpace + "." + TypeName);

            
Labs3.ITest obj2 (Labs3.ITest) Activator.CreateInstance(t);
            
obj2.Method();

            
Console.ReadLine();

        
}
    }

}

namespace Labs2
{
    
public abstract class Test
    {
        
public virtual void Method()
        {
            Console.WriteLine(
"BasedTest2");
        
}
    }

    
public class DerivedTest : Test
    {
        
public override void Method()
        {
            Console.WriteLine(
"DerivedTest2");
        
}
    }
}

namespace Labs3
{
    
interface ITest
    {
        
void Method();
    
}
    
    
public class Test : ITest
    {
        
public virtual void Method()
        {
            Console.WriteLine(
"BasedTest3");
        
}
    }
   
    
public class DerivedTest : Test
    {
        
public override void Method()
        {
            Console.WriteLine(
"DerivedTest3");
        
}
    }
}

Wednesday, November 21, 2007

What is the use of 'virtual new' keyword ?

using System;
using 
System.Text;

namespace 
Polymorphism
{
    
class Program
    {
        
static void Main(string[] args)
        {
            Derived1 dv1 
= new Derived1();
            
//Do you know which Class Method is called here ?
            
dv1.Method(dv1);

            
Derived2 dv2 = new Derived2();
            
//Do you know which Class Method is called here ?
            
dv2.Method(dv2);

            
DerivedDerived3 dv3 = new DerivedDerived3();
            
//Do you know which Class Method is called here ?
            
dv3.Method(dv3);

            
DerivedDerived4 dv4 = new DerivedDerived4();
            
//Do you know which Class Method is called here ?
            
dv4.Method(dv4);

            
Console.ReadLine();
        
}
    }

    
class Based1
    {
           
public string Display()
           {
               
return "based";
           
}
     }
     
    
class Derived1:Based1
    {
        
//What is the use of new keyword ?
           
public new string Display() 
           {
               
return "derived";
           
}
    
        
public void Method(Based1 t)
        {
              Console.WriteLine(t.Display())
;
        
}
    }

    
class Based2
    {
        
//What is the use of virtual keyword ?
        
public virtual string Display()
           {
               
return "based";
           
}
     }

    
class Derived2 : Based2
    {
        
//What is the use of override keyword ?
        
public override string Display()
        {
            
return "derived";
        
}

        
public void Method(Based2 t)
        {
            Console.WriteLine(t.Display())
;
        
}

    }

    
class Based3
    {
        
public string Display()
        {
            
return "based";
        
}
    }
    
    
class Derived3 : Based3
    {
        
//What is the use of 'virtual new' keyword ?
        //Methods of a derived class can both be virtual and at the same time hide the derived method. 
        //In order to declare such a method, both keywords virtual and new have to be used in the method declaration
        
public virtual new string Display()
        {
            
return "derived";
        
}
    }

    
class DerivedDerived3 : Derived3
    {
        
public override string Display()
        {
            
return "derivedderived";
        
}

        
public void Method(Derived3 t)
        {
            Console.WriteLine(t.Display())
;
        
}
    }

    
class DerivedDerived4 : Derived3
    {
        
public new string Display()
        {
            
return "derivedderived";
        
}

        
public void Method(Derived3 t)
        {
            Console.WriteLine(t.Display())
;
        
}
    }

}

 

Friday, November 16, 2007

C# Syntax Cheat Sheet


x       Indicates x is supplied by the programmer or to be used verbatim
x?      Indicates x may occur zero-or-one times
x*      Indicates x may occur zero-or-more times, separated by commas
x+      Indicates x may occur one-or-more times,  separated by commas
[...]   Indicates a logical grouping of code elements, when not implicitly grouped using the verbatim 
terms {}, (), and []
[x|y]   Indicates only one of a choice of code elements may occur


 


Expression Statements


[variable = ]? expression;


 


Variable declaration        


type [variable [ = expression ]?]+ ;


 


Checked/unchecked operator


checked (expression)


unchecked (expression)


 


Checked/unchecked statement


Checked  statement-or-statement-block


Unchecked statement-or-statement-block


 


new operator 


class-var = new class-name();


 


Constant declaration       


const type [variable = constant-expression]+ ;


 


if-else statement


if (Boolean-expression)


statement-or-statement-block [


else


statement-or-statement-block ]?


 


switch statement


switch (expression) {


[ case constant-expression : statement* ]*


[ default : statement* ]? }


 


while loops


while (Boolean-expression) statement-or-statement-block


 


do-while loops


do


statement-or-statement-block while (Boolean-expression);


 


 


for loops


for (statement?; Boolean-expression?; statement?)


statement-or-statement-block


 


foreach loops


foreach ( type-value in IEnumerable) statement-or-statement-block


or


foreach(type var-name in collection) statement


 


goto statement :


goto statement-label;


goto case-constant


 


return statement


return expression?;


 


throw statement     


throw exception-expression?;


or


throw exceptOb;


The exceptOb must be an object of an exception class derived from Exception.


 


lock statement


lock (expression) statement-or-statement-block


 


using statement


using (declaration-expression) statement-or-statement-block


 


 


Namespace declaration syntax:


namespace name+ {


   using-statement*


   [namespace-declaration | type-declaration]*


}


 


Class


attributes? unsafe? access-modifier?


new?


[ abstract | sealed ]?   


class class-name [: base-class | : interface+ |: base-class, interface+ ] ?


{ class-members }


 


 


interface declaration:


interface name {


  ret-type method-name1(param-list);


  ret-type method-name2(param-list);


  // ...


  ret-type method-nameN(param-list);


}


 


interface property


type name {


  get;


  set;


}


 


interface indexer


element-type this[int index] {


  get;


  set;


}


 


Fields


attributes? unsafe? access-modifier? new?


static?


[readonly | volatile]?


type [ field-name [ = expression]? ]+ ;


 


 


Struct


attributes? unsafe? access-modifier?


new?


struct struct-name [: interface+]?


{ struct-members }


 


  


Constant 


attributes? access-modifier?


new?


const type [ constant-name = constant-expression ]+;


 


 


Properties


attributes? unsafe? access-modifier?


[


[[sealed | abstract]? override] |    


new? [virtual | abstract | static]?


]?


type property-name { [    


attributes? get statement-block |    //     read-only


attributes? set statement-block |    //      write-only


attributes? get statement-block      //     read-write


attributes? set statement-block ] 


}


 


Indexers


attributes? unsafe? access-modifier?             


[                 


  [[sealed | abstract]? override] |           


  new? [virtual | abstract]?            


]?               


type this [ attributes? [type arg]+ ]      {       


attributes? get statement-block |  //       read-only


attributes? set statement-block |  //       write-only


attributes? get statement-block    //       read-write


attributes? set statement-block             


}


 


Method


attributes? unsafe? access-modifier? [


[[sealed | abstract]? override] |


new? [ virtual | abstract ]?


[ void | type ] method-name (parameter-list) statement-block


 


 


Parameter list


[attributes? [ref | out]? type arg ]* [ params attributes? type[ ] arg ]?


 


 


Instance Constructors


attributes? unsafe? access-modifier?


class-name (parameter-list) [ :[ base | this ] (argument-list) ]?


statement-block


 


calling base class contructor :


derived-constructor(parameter-list) : base(arg-list) {


   // body of constructor


}


 


Static Constructors


attributes? unsafe? extern? static class-name ( ) statement-block


 


Destructors and Finalizers


attributes? unsafe? ~class-name () statement-block


 


Interfaces


attributes? unsafe? access-modifier? new?


interface interface-name [ : base-interface+ ]? { interface-members }


 


 


Arrays


type[*]+ array-name = new type [ dimension+ ][*]*;


 


[*] is the set: [] [,] [,,]


 


Initializing a one-dimensional array


type[ ] array-name = { val1, val2, val3, ..., valN };


 


 


Enums


attributes? access-modifier?


new?


enum enum-name [ : integer type ]?


{ [attributes? enum-member-name [ = value ]? ]* }


 


 


Delegates


attributes? unsafe? access-modifier? new?


Delegate [ void | type ]  delegate-name (parameter-list);


 


Delegate-invocations


primary-expression-of-a-delegate-type (expression);


 


Delegate-creation


new   delegate-type  (expression);


The argument of a delegate creation expression must be a method group or a value of a delegate-type.


 


Events


access-modifier? event event-delegate object-name;


 


Event Accessors


 attributes? unsafe? access-modifier?


[


  [[sealed | abstract]? override] | new? [virtual | static]?


]?


event delegate type event-property-accessor-name


{


attributes? add statement-block


attributes? remove statement-block


}


 


 


try statement


try statement-block


[catch (exception type value?)? statement-block]+  | finally statement-block |


[catch (exception type value?)? statement-block]+     finally statement-block


 


 


Attributes


[[target:]? attribute-name


(


positional-param+ |


[named-param = expression]+ |


positional-param+, [named-param = expression]+)?]


 


overloading a unary operator


public static ret-type operator op(param-type operand)


{


   // operations


}


 


overloading a binary operator


public static ret-type operator op(param-type1 operand1, param-type1 operand2)


{


   // operations


}


 


 


NET-compatible event handlers 


void handler(object source, EventArgs arg) {


  // ...


}


 


Delegates


public delegate  void  Del<T>(T item);


public void Notify(int i) { }


 


Del<int> d1 = new Del<int>(Notify);


 


In C# 2.0


 


Del<int> d2 = Notify;


 


 


generic class


class class-name<type-param-list> { // ...


 


declaring a reference to a generic class


class-name<type-arg-list> var-name =


new class-name<type-arg-list>(cons-arg-list);


 


generic method


ret-type meth-name<type-parameter-list>(param-list) { // ...


 


generic delegate


delegate ret-type delegate-name<type-parameter-list>(arg-list);


 


 


References :
C# Essentials, 2nd Edition, Ben Albahari Peter Drayton Brad Merrill
Microsoft Visual C# .NET,
http://msdn.microsoft.com/vcsharp
ECMA C# Standard, http://www.ecma.ch/ecma1/stand/ecma-334.htm


 

Tuesday, November 6, 2007

Value vs Reference Types

//The stack is always used to store the following two things
// 1> The reference portion of reference-typed local variables and parameters
// 2> Value-typed local variables and method parameters
//The following data is stored on the heap:
// 1> The content of reference-type objects.
// 2> Anything structured inside a reference-type object.

public class A
{
      private int myVar;

      public int 
MyVar
      {
         get return myVar}
         set { myVar = value; }
      }
}


public class Test1
{
      public void TestMain()
      {
          //we create a local variable that references an object.
          //The local variable is stored on the stack,
         //while the object itself is stored on the heap
          A a = new A();
          a.MyVar 0;
         //In C#, parameters are (by default) passed by value,
         //meaning that they are implicitly copied when passed to the method
         Pass(a);
      }

      public void Pass(A x)
      {
          //at this line x and 'a' still point to the same object
          //So this will be change on 'a.MyVar' to 9
          x.MyVar 9;
          //Even this No effect on 'a' since x is a copy
          x = null;
          A b = new A();
          x b;
         //at this line x and 'a' point to different object
         //So this will be NO change on 'a.MyVar'
         x.MyVar 1;
      }
}

public class Test2
{
      public void TestMain()
      {
         A a 
= new A();
         a.MyVar 0;
         //When passing by "reference", the method interacts directly with the caller's arguments.
         Pass(ref a);
      }

      public void Pass(ref A x)
      {
         A b 
= new A();
         b.MyVar 1;
         //This will change 'a' pointer
         x b;
         // now 'a.MyVar' = 1

         //In this case, assigning null to x also makes 'a' null, because this time were
         //dealing with the original reference variable and not a copy of it.
         x = null;
      }
}
Indonesia To Blog -Top Site
SEO - search engine submission and optimisation