Vivek 的个人资料A Developer's Experience照片日志列表更多 工具 帮助

日志


The Constraint Of Constraints !!!

I was happy programming with (generic) constraints which overtook the limitations in C++ templates. However, constraints need to be less restrictive. What is that? Let us say I want a helper method that checks a condition and throws an exception if the check failed. So that would be...

void TestCondition(bool condition, string msgText)
{
    if (!condition)
    {
        throw new Exception(msgText ?? "Unknown Error");
    }
}

I like it; it is cute. However, not at all times would the caller be happy with throwing System.Exception. Since the above method can be used in a wide variety of situations, it would make sense for the caller to specify the type of exception he would like to throw. It would be classic if the above is made generic taking type T and constraining it be to a derivate of System.Exception. Sounds great and so…

void TestCondition2<T>(bool condition, string msgText) where T : Exception
{
    if (!condition)
    {
        throw new T(msgText ?? "Unknown Error");
    }
}

The above code is dream still; it will result in a compilation error. Although generics offers the constraint that T should be a derivate of System.Exception, it does not relax it specifying the constructor it would like to use from T; in other words, there is constraint mandating T to expose a default constructor but none other. So we cannot offer the above facility with elegance (or performance?). There is the ugly way. How?

void TestCondition3(bool condition, Exception ex)
{
    if (!condition)
    {
        throw ex;
    }
}

Seems good? Partly No. If TestCondition2 was possible, the exception object(s) would be created only if the condition failed, while TestCondition3 meeting our purpose creates exception objects irrespective of the condition; and gets thrown if the condition fails.

So when are (generic) constraints going to be relaxed? C# 5.0?

Curious Case Of Anonymous Delegates !!!

Senthil has left us thrilled in his new post, and also inspired me to write about the topic. Although, anonymous delegates have become a mundane stuff amongst programmers, there is still these subtle stuff left unexplored. Alright, let us try to answer Senthil's question before he unravels the mystery in his next post.

A delegate is identified by its target. The target is the method to be executed on a delegate invocation and its associated instance or type. If the target is an instance method, the delegate preserves the target method pointer and the object instance. If the target is a static method, the delegate preserves the target method pointer and the type to which it belongs. So when a code like the one below to register a method to an event (or multicast delegate) is executed, a delegate object (EventHandler here) with the target information embedded is created and added to the invocation list of the event (or multicast delegate, KeyPressed here).

class SomeForm
{
	private Control control = new Control();

	public void OnFormLoad(object sender, EventArgs args)
	{
		control.KeyPressed += new EventHandler(OnKeyPressed);
	}
	
	// Rest of the code omitted to be succinct
};

Likewise, when unregistering the method handler, a new (EventHandler) delegate object is created with the same target information as above. As said earlier, a delegate is identified by its target. In other words, the Equals override on the delegate uses the target information for comparing two delegate objects. Hence in the following code that unregisters the method handler, the invocation list is searched for a delegate instance with the specified target information (Method: OnKeyPressed, Instance: SomeForm instance).

In the case of anonymous delegates, the compiler transforms the inline method code into a

  • static method, if the inline method code does not use any of the class's instance members or local variables or if it uses only the static members of the class.
  • instance method, if the inline method code uses at least one class member, any or no static members, and no local variables.
  • class with a method that represents the inline method code, if the inline method code uses local variables no matter whether it uses the class members or not.

Those might not be the extensive set of rules but sure are enough for our discussion. Given the following questionable code,

public EventHandler IfEnabledThenDo(EventHandler actualAction)
{
	return (sender, args) => { if (args.Control.Enabled) { actualAction(sender, args); } };
}

public void Initialize()
{
	control.KeyPressed += IfEnabledThenDo(control_KeyPressed);
}

public void Destroy()
{
	control.KeyPressed -= IfEnabledThenDo(control_KeyPressed);
}

we realize, without doubt, that the anonymous delegate (returned by IfEnabledThenDo) would be transported into a compiler generated anonymous class. Later when IfEnabledThenDo is called for registering\unregistering the method handler, an instance of anonymous class is created and the (EventHandler<Control.ControlEventArgs>) delegate is returned. And here lies the subtlety. Although the delegate from IfEnabledThenDo targets the method inside the anonymous class, the instance preserved as a part of the target information are different during registration and un-registration. In other words, the target method of the delegate returned by IfEnabledThenDo belong to different instances of the anonymous class. Hence the pretty code to unregister the (key pressed) method handler would not be actually unregistering since there would be a delegate previously registered in the invocation list of the (KeyPressed) event with the target instance same as the one used in the unregistration line of code. Very subtle!

Usually the hand written code tends to keep the registration and unregistration of the method handlers in the same class and so belong to the respective instances. Not so when you like watching the compiler magic.

Let us wait and see what Senthil says.

(Re)declaring event Members !!!

Sanjeev wondered why should an event decalred in an interface be declared in the implementation class too. For instance if we have an interface ISample as follows:-

public delegate void DataChangedDelegate(int dataID, object newData);
public interface ISample
{
    event DataChangedDelegate dcDelegate;
    void SomeMethod(); 
    bool SomeMethod(int x);
}

and a class that implements ISample (implicitly):-

public class SampleImpl : ISample
{
    public SampleImpl()
    {
    }

    #region ISample implicit implementation

    // Why is this required to be done?
    public event DataChangedDelegate dcDelegate;

    public void SomeMethod()
    {
    }

    public bool SomeMethod(int x)
    {
        return x >= 0 ? true : false;
    }

    #endregion
}

While we define the implementation of the methods from ISample in SampleImpl, we dont do anything (special) to implement the event. So why should SampleImpl simply declare the event once again? Of course, it is convince to compiler from spitting errors.

It is time to know what is an event? The event keyword when decorated for a delegate declaration ensures that only the class\struct in which the event is declared will be able to raise event, irrespective of its access levl. In other words, only the owning class\struct will be able to call the subscribers. So that will prevent anybody outside the declaring class to misuse the delegate - raise false events - especially when the delegate is declared public.

Good, but still there is a way to tamper the delegate. Anybody could add or especially remove the subscribers from the delegate (when it is exposed public). The event keyword does more than preventing unauthorised use of the delegate to raise events. It is a compiler acronymn for methods by which handler targets can be added and removed from the delegate. We can say it is analogous to the properties which provide get and set methods. An event is not like an ordinary member declaration - int, float or delegate for that matter, and interfaces cannot bear member declarations.

In essence, an event declaration in the interface opens up during compilation as follows:-

// add and remove are like get\set in a property.
event DataChangedDelegate dcDelegate { add; remove; } 

The add and remove have to implemented in the derived class. Declaring the event in the derived class instructs the compiler to generate default implementation for add and remove methods, something like what the automatic properties do. If one wants to take control of adding and removing handlers with some custom logic, he/she can do so by explicitly implementing add\remove methods.

private DataChangedDelegate dcSubscribers;
public event DataChangedDelegate dcDelegate
{
    add
    {
        if (value == null)
        {
            throw new Exception("Specified null event handler");
        }

        lock (dcSubscribers)
        {
            dcSubscribers += value;
        }
    }
    remove
    {
        if (value == null)
        {
            throw new Exception("Specified null event handler");
        }

        lock (dcSubscribers)
        {
            dcSubscribers -= value;
        }
    }
}

And SomeOtherMethod in the derived class could fire the event.

public bool SomeOtherMethod(int x)
{
    DataChangedDelegate tempDC = dcSubscribers;
    if (tempDC  != null)
    {
        tempDC(x, DateTime.Now);
    }

    return x > 0 ? true : false;
}

So that's why it is necessary to declare an event member when deriving from an interface.

finally and Return Values !!!

Let us read some code:-

int SomeMethod()
{
    int num = 1;

    try
    {
        num = 5;
        return num;
    }
    finally
    {
        num += 5;
    }
}

What is the return value of SomeMethod? Some anonymous guy asked that question in the code project forum, and it has been answered. I am writing about it here because it is interesting and subtle. One should not be surprised when people misinterpret finally. So let us take a guess, 10 (i = 5, then incremented by 5 in the finally block).

It is not the right answer; rather SomeMethod returns 5. Agreed that finally is called in all cases of returning from SomeMethod but the return value is calculated when it is time to return from SomeMethod, normally or abnormally. The subtlety lies not in the way finally is executed but in the return value is calculated. So the return value (5) is decided when a return is encountered in the try block. The finally is just called for cleanup; and the num modified there is local to SomeMethod. So make the return value 10, it is no use being hasty making SomeMethod return from the finally block. Because returning from finally is not allowed. (We will talk about it later why returning from catch block is a bad practice and why can't we return from finally block).

Had such modifications been done on a reference type, they would have been visible outside of SomeMethod, although the return value may be different. For instance,

class Num
{
    public int _num = 0;
};

int SomeMethod()
{
    Num num = new Num();

    try
    {
        num._num = 5;
        return num._num;
    }
    finally
    {
        num._num += 5;
    }
}

So in the above case, the return value is still 5, but the Num._num would have been incremented to 10 when SomeMethod returns. So reflecting shows that our code is transformed as follows by the compiler, where the CS$1$0000 is our return value.

private static int SomeMethod(Num num)
{
    int CS$1$0000;
    try
    {
        num._num = 5;
        CS$1$0000 = num._num;
    }
    finally
    {
        num._num += 5;
    }
    return CS$1$0000;
}

Given that we have clarified ourselves about finally, we should be writing the code as transformed by the compiler because returning from try and catch blocks is not a good practice.

OrderedThreadPool - Task Execution In Queued Order !!!

I would not want to write chunks of code to spawns threads and perform many of my background tasks such as firing events, UI update etc. Instead I would use the System.Threading.ThreadPool class which serves this purpose. And a programmer who knows to use this class for such cases would also be aware that the tasks queued to the thread pool are NOT dispatched in the order they are queued. They get dispatched for execution in a haphazard fashion.

In some situations, it is required that the tasks queued to the thread pool are dispatched (and executed) in the order they were queued. For instance, in my (and most?) applications, a series of events are fired to notify the clients with what is happening inside the (server) application. Although the events may be fired from any thread (asynchronous), I would want them or rather the client would be expecting that the events are received in a certain order, which aligns with the sequence of steps carried out inside the server application for the requested service. So sequential execution of the queued tasks is not something one must not wish for.

Enough talking.......eat code.

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace System.Threading
{
   struct ThreadPoolTaskInfo
   {
      public readonly WaitCallback CallbackDelegate;
      public readonly object State;

      public ThreadPoolTaskInfo(WaitCallback wc, object state)
      {
         Debug.Assert(wc != null);
         CallbackDelegate = wc;
         State = state;
      }
   }

   class OrderedThreadPool
   {
      private Queue workItemQ = new Queue();

      public void QueueUserWorkItem(WaitCallback wcbDelegate, object state)
      {
         lock (workItemQ)
         {
            workItemQ.Enqueue(new ThreadPoolTaskInfo(wcbDelegate, state));

            if (workItemQ.Count == 1)
            {
               ThreadPool.QueueUserWorkItem(LoopWork);
            }
         }
      }

      private void LoopWork(object notUsed)
      {
         WaitCallback wcb = null;
         object state = null;

         lock (workItemQ)
         {
            if (workItemQ.Count == 0)
            {
               return;
            }

            ThreadPoolTaskInfo tptInfo = workItemQ.Dequeue();
            state = tptInfo.State;
            wcb = tptInfo.CallbackDelegate;
            Debug.Assert(wcb != null);
         }

         try
         {
            wcb(state);
         }
         finally
         {
            ThreadPool.QueueUserWorkItem(LoopWork, notUsed);
         }
      }
   }
}

The above class wraps the System.Threading.ThreadPool and offers the facility of execution of tasks in the order they are queued. Hope that is useful!

Understanding (ref)erences !!!

Let us take a look at the following piece of code:-

public void Operate(IList iList2)
{
    iList2 = new List();
    iList2.Add(1);
    iList2.Add(2);
    iList2.Add(3);
}

public static void Main()
{
    IList iList= new List();
    iList.Add(10);

    Operate(iList);

    Console.WriteLine(iList[0].ToString());
}

Be thinking about what would the above program print to the console ? And that is what we are going to talk about in this post - simple but subtle.

I saw this code at CodeProject discussions. The author was confused with why was the program printing 10 instead of 1. I am writing about this since the 'gotcha' was not highlighted in the discussion.

So we passed the reference 'iList' to the function which is supposed to make it point to the 'List' that it creates and so must be printing 1. Well, a C++ programmer knowing how to program in C# would have said 'Gotcha' already. A reference (in C#), equivalent to a pointer in C++, is an entity that stores the address of an object in heap and accesses it using this address. So when we pass a reference (by value) to a function, then we are passing this address value. That is captured in another 4 byte variable local to that function; so creating assigning inside the function will make iList2 point to newly created object - iList and iList are two different reference pointing to the same object. So if you want to transmit the effect of the changes you make to the List inside the function, pass it by reference - use ref keyword.

Now the fun part !!! Let us try writing the same stuff in C++:-

// This function will not alter the source pointer
public void Operator(IList* pList)
{
	pList = new List();
	pList->Add(1);
	pList->Add(2);
	pList->Add(3);
}

// This function will affect the source; similar to using ref in C#
// 1) const IList*& pList - Can make pList point elsewhere but cannot modify the existing object
// 2) IList* const &pList - pList cannot point to anywhere else but can modify the existing object
public void Operator(IList*& pList)
{
	pList = new List();
	pList->Add(1);
	pList->Add(2);
	pList->Add(3);
}

Hope that was fun !!!

(Generic) Type Inference & Intellisense !!!

Consider this:-

class CmdBase
{
	public char ReturnValueFromBase()
	{
	}
}

class ReadCmd : CmdBase
{
	// No time for ctor coding

	public bool ReturnValueFromRead()
	{
	}
}

class WriteCmd : CmdBase
{
	// No time for ctor coding

	public int ReturnValueFromWrite()
	{
	}
}

// And imagine exactly 212 other such commands, just kidding; the above two would do fine for now.

Now let us say we want to write a method which could execute any given command (a derivate of CmdBase), and as you can see must be to retrieve the command specific return value (via the ReturnValeFromXXX method). So...

T Execute<T>(T cmdObj) where T : CmdBase
{
	// Execute the command by any way you like
return cmdObj; }

You can call Execute in one of the following ways:-

Execute<ReadCmd>(new ReadCmd(/*parameters*/).ReturnValueFromRead();

or

Execute(new ReadCmd(/*parameters*/).ReturnValueFromRead();

Is there any difference in the above two ways ? Ideally, none. Wierd that the intellisense does not infer the exact type for the second way; instead assumes the type passed as CmdBase. But the code compiles and executes fine (as written and as expected). So is that a bug in the intellisense or is that intentional ?

Scrollable Image Viewer !!!

Every time I find it hard with these Microsoft guys. They are smart, I agree. But frequently they miss out vital features in the products they deliver. Something like the picture box control without the facility to view the image with scrolling. I had this situation where I needed a (picture box like) control which must be able to display images in one of the two modes - Blown-up or Full Image.

So what are these two modes ? That is a story a bit big for this post. I have posted an article in Code Project that talks about our control Scrollable Image Viewer control. Go have a look at it and sure you may find it useful in your applications too. In that case, you are free to use and distribute (CPOL). Oh......bugs are your burden.

If there are any bugs or if you have any suggestions about other improvements in code, let me know.

A Life Without Friends !!!

Can you imagine a life without friends ? I would say it would be miserable. It is a great deal of trust and sharing; you expose your private stuff and she too does, you know it is great. That makes tough tasks come down low. But it is your responsibility to choose who your friends are, else you are going to hurt yourself. Hey, I am talking C++. Friend functions and classes are real sweet, but you have to be careful in your judgment.

Ok, why are we talking this ? It is a common scenario where there is a class which acts as a manager and manages instances of an other class. Need an example, imagine this - Let us say that we have an Employee class which describes an employee (ID, Name, Salary, DOB etc). At first look, we can easily say that his ID is his private stuff, and also it must be unique. So if we are creating a new instance of an Employee, it must be ensured that the ID is indeed unique. That means that just a public method on Employee to set the ID or a one time set in the Employee constructor is not enough. So we can have a Supervisor class that has the manages the list of employees. Too much talk, let us see code with Supervisor being friendly with the Employee.

// Forward Declaration
class Supervisor;

class Employee
{
private: int _id;
private: std::string _name;
private: float _salary:
private: DateTime _dob;
private: int _designationLevel;

private: Employee(int id,
            const std::string& name,
            const DateTime& dob,
            int designationLevel)
         {
            this->_id = id;
            this->_name = name;
            this->_designationLevel = designationLevel;
            this->_salary = designationLevel * 1000;
            this->_dob = dob;
         }

         // private set methods for the data members
private: void ChangeName(const std::string& newName)
         {
            this->_name = newName;
         }

private: void UpdateDesignation(int dLevel)
         {
            this->_designationLevel  = dLevel;
            this->_salary = dLevel * 1000;
         }

         // private get methods for the data members
public: int ID() const { return this->_id; }
public: int Name() const { return this->_name; }
public: DateTime DOB() const { return this->_dob; }
public: int DesignationLevel() const { return this->_designationLevel; }
public: float Salary() const { return this->_salary; }

        friend class Supervisor;
};

class Supervisor
{
public: std::list<Employee*> employeeList;

public: Employee* AddNewEmployee(const std::string& name, int designationLevel)
        {
           int id = GenerateUinqueID();
           return new Employee(id,
              name,
              "12-JUNE-1980",
              designationLevel);
        }

public: void ChangeEmployee(const Employee& emp, const std::string& newName)
        {
           std::list<Employee>::iterator iter = employeeList.end();
           iter = std::find(employeeList.begin(), employeeList.end(), emp);

           if (iter != employeeList.end();)
           {
              (*iter)->ChangeName(newName);
           }
        }

public: void Promote(const Employee& emp)
        {
           std::list<Employee>::iterator iter = employeeList.end();
           iter = std::find(employeeList.begin(), employeeList.end(), emp);

           if (iter != employeeList.end();)
           {
              (*iter)->UpdateDesignation(emp->DesignationLevel()++);
           }
        }
};

That is the not the best code you have ever seen, but let us stick to the theme of the post - friends ! So the Supervisor is a friend of Employee and so is it the only privileged one to create and modify the Employee class. Most important (in many cases), an instance of Employee cannot be created by anybody, say with duplicate or invalid IDs.

When C++ is cursed for the friend facility, which some people think is a tweak or a loop hole for the data privacy, I would say that it is a finely thought one and must be used with judgement. It is not for the weak hearted ones. I have used a lot in many of my projects with care, caution and rationale.

So, there is no friend facility in C#. Atleast, I am not aware of one such. My code looks horrible for a design discussed above. So is there an alternative approach (of design) in C# for the above mentioned problem ?

The question is open to all. Got any idea or a solution ?

Speculating 'this' !!!

Imagine a class written as shown below:-

public partial class HardwareUI : UserControl
{
   private bool advancedOpen = false;
   private int CollapsedContainerWidth = 170;
   private int ExpandedContainerWidth = 510;

   // Default Ctor
   public HardwareUI() : this(this.CollapsedContainerWidth, this.ExpandedContainerWidth)
   {
   }

   // 2Arg Ctor
   public HardwareUI(int collapsedParentHeight, int ExpandedContainerWidth)
   {
      InitializeComponent();

      if (collapsedParentHeight > 0)
      {
         this.CollapsedContainerWidth = collapsedParentHeight;
      }

      if (ExpandedContainerWidth > 0)
      {
         this.ExpandedContainerWidth = ExpandedContainerWidth;
      }
   }

// Other Code
}

I have shown that part of the class that is pertaining to the theme of this post. So hold on a while if you feel that the class is inadequate or wrongly written.

The compiler spat an error - "Keyword 'this' is not allowed in the current context". That is what I am suprised about. Why cannot I use the 'this' in the ctor ? The following two things should have been done (in order of apperance) when the execution reaches the ctor :-

  • Object memory allocation
  • Field initializations (static and instance)
  • Base class ctors are executed

    In our case, there are no base classes. So when we are at the ctor, the fields must have been initialized. Is that right ? Well, that is the hazy part; and it depends how the fields are used and the way the ctors are written.

    In the case (code as above), the actual field initialization happens in the 2Arg Ctor. That means the fields initialization code is injected in the 2Arg ctor code. After all, ctors are also methods (but special). And in our case, when the default ctor is called, it just prepares the call for the 2Arg ctor. So the fields are not initialized, and we know C# prohibits the usage of uninitialized variables. And the error that the compiler spat is a manifestation of the above rule. But what if I rewrite my class this way:-

    // NEW Default Ctor
    public HardwareUI() : base(this.CollapsedContainerWidth, this.ExpandedContainerHeight)
    {
        InitializeComponent();
    }
    
    // NEW 2Arg Ctor
    public HardwareUI(int collapsedParentHeight, int ExpandedContainerWidth)
        : base(this.CollapsedContainerWidth, this.ExpandedContainerHeight)
    {
       InitializeComponent();
    
       if (collapsedParentHeight > 0)
       {
          this.CollapsedContainerWidth = collapsedParentHeight;
       }
    
       if (ExpandedContainerWidth > 0)
       {
          this.ExpandedContainerWidth = ExpandedContainerWidth;
       }
    }
    

    Following are the changes made to the class:-

  • Derived the class from a base class [say HeightInfo, who ctor takes 2 arguments]
  • Modified the ctors to be non-delegating

    The compiler spits the same error - 'Keyword 'this' is not available in the current context'. Fine. But for this modified case, if there is no base class derivation, then the field initialization code will be stuffed in both the ctors. So why not allow to access the member fields in the modified class ? Is that an ignorant or unwise expectation ? Might be. I am not sure what I am missing here ? If you guys can correct me or educate me on this, that might be helpful.

    Senthil's post might also be a useful source in our attempts to understand the restriction.

  • Generics without <> !!!

    I have been using generics - classes and methods for a long time now. Also I have implemented a few generic classes and methods myself. For instance, I use the Array.Exists<> or Find<> or ForEach<> a lot without bothering about the performance and stuff. They are very easy and handy to use. This is a normal way you use a generic method in Array:-

    string[] subsetNames = Array.FindAll<string>(namesArray, delegate(string name)
    {
        return name.Contains("gu");
    });
    

    And the <string> in the above code specifies the generic parameter. Recently I wrote some code [unknowningly] like the one above but a bit different:-

    string[] subsetNames = Array.FindAll(namesArray, delegate(string name)
    {
        return name.Contains("gu");
    });
    

    Looks the same ? Watch it close. I did not specify the generic parameter. But the above still works fine. I was surprised to know that the generic parameters need not be explicitly specified mandatorily unlike C++ template methods. The C# compiler infers the types from the parameters passed. So the responsibility of genericity is not strictly imposed on the caller but on the method called which must take care of the job to be done irrespective of types, and the C# compiler helps in a very nifty way to make the code a bit cool. That being said, if you have a generic method like this in one of your classes:-

    public bool SomeMethod(P1 paramOne, P2 paramTwo)
    {
        Console.WriteLine("{0}, {1}", paramOne, paramTwo);
        return true;
    }
    

    it can be called like this:-

    instance.SomeMethod("Hello", 2007);
    instance.SomeMethod(myclassType, yourclassType);
    

    instead of

    instance.SomeMethod<string, int>("Hello", 2007);
    instance.SomeMethod<MyClass, YourClass>(myclassType, yourclassType);
    

    People may prefer to use the non-nifty way and may argue that the clarity in the code is lost if the generic parameter types are not specified. Well, I feel that the type identity is already with the parameters being passed, and nobody can change that. Also the compiler spits errors for wrong types if you try something like this:-

    string[] namesArray = initialize with an array of strings;
    string[] subsetNames = Array.FindAll(namesArray, delegate(int name)
    {
        // return name.Contains("gu");
        return true;
    });
    

    I prefer to skip specifying the <> for type information since the code above will result in wrong type specification error like the one below:-

    string[] namesArray = initialize with an array of strings;
    string[] subsetNames = Array.FindAll(namesArray, delegate(int name)
    {
        // return name.Contains("gu");
        return true;
    });
    

    So the <> is an ease of syntax and does not compromise the type and identity.

    There is nothing special about this but that after using templates for a while, generics seems to help avoid reiterating the type information. Type and Identity are considered very sacred in the managed world. May be that is special and its manifestation is well seen through this nifty syntax for generics.

    Will post on this if there is anything else special.

    The Surprising Finalize Call !!!

    Guess the output of the following program:-
     
    class SomeClass : IDisposable
    {
       public SomeClass()
       {
          Trace.WriteLine("SomeClass - Attempting instance creation");
          throw new Exception("Ohh !!! Not Now");
       }
      
       public void Dispose()
       {
          Trace.WriteLine("SomeClass::Dispose");
       }
      
       ~SomeClass()
       {
          Trace.WriteLine("SomeClass::Finalizer");
       }  
    }
     
    int Main(string args[])
    {
       try
       {
          SomeClass sc = new SomeClass();
       }
       catch(Exception ex)
       {
          Trace.WriteLine("Main - {0}", ex.Message);
       }
    }
     
    This will be the output of the program:-
     
    SomeClass - Attempting instance creation
    Ohh !!! Not Now
    SomeClass::Finalizer
     
    If you are surprised with the last line of the output, that will be the intent of our discussion. In the .NET [managed] world, the garbage collector is entirely responsible for memory management - allocation and deallocation. In C#, an instance of a class is created using the new keyword. When an instance creation is requested, first memory for the instance is allocated followed by a call to the [appropriate] constructor of the class.
     
    To explain the surprising output, the constructor is called after the memory is allocated by the GC. When the constructor throws exception, the object or resource creation is interrupted but the memory cannot deallocated instantly since the GC is entirely responsible for memory deallocation. The GC follows a complex and non-deterministic style for deallocating or reclaiming an allocated chunk of memory. The finalizer method is the last call made on a managed object just before reclaiming memory. Hence in the above case, the finalizer is being called before reclaiming the memory allocated for an instance of SomeClass.
     
    The above behaviour is very much different from the unmanaged C++ where when the instance creation is interrupted [by throwing an exception], the allocated memory is deallocated and reclaimed instantaneously. Also the destructor is not called in this case.
     
    P.S: Thinking of a more detailed post on non-deterministic destruction.

    Learning Type Access Modifiers Basics !!!

    When I started developing my module, I had an interface IParamCountBasedAlgo declared as a nested type in a class AlgorithmOneExecutor, declared as follows:-

    namespace DataStructuresAndAlgo
    {
      partial class AlgorithmOneExecutor
      {
         private interface IParamCountBasedAlgo
         {
            void Validate();
            void Execute();
         }
      }
    }

    There were other concrete nested types inside AlgorithmOneExecutor that implemented IParamCountBasedAlgo. But later,  other types nested in other than AlgorithmOneExecutor emerged that required to implement IParamCountBasedAlgo. So I moved IParamCountBasedAlgo from a nested type to a direct type under the namespace DataStructuresAndAlgo, as declared below:-

    namespace DataStructuresAndAlgo
    {
      private interface IParamCountBasedAlgo
      {
         void Validate();
         void Execute();
      }
    }

    And the compiler spat an error "Namespace elements cannot be explicitly declared as private, protected, or protected internal". Then a simple research gave me an insight that types directly under namespace can be declared either public or internal only, and the default is internal. Seems reasonable cuz if declared private, it gives an ambiguous look that it cannot accessed or created and protected seems rather very unrelated. Hence either public or internal only.

    A subtle point to note is that not all access modifiers are applicable for all types and at all declaration levels. To learn the basics of type access modifiers, visit http://msdn2.microsoft.com/en-us/library/ms173121.aspx

    where enum does not work !!!

    I was writing a generic method with enum as the Constraint, and the compiler spat a few errors that did not directly convey me that enums cannot used as generic constraints. And I learnt the following from my investigation:-

    This is an excerpt from the C# Language Specification. Enums are value types and there is no way that you can specify the System.ValueType as a constraint, as per the specification. But if you wish to specify a non-reference type as a [primary] constraint, struct can be used.

    private void Method<T>where T : struct

    That does not guarantee that our generic method will not accept other value types, besides enum, for which we do not support our functionality.

    During the course of investigation, I was extremely surprised to know that the numeric types like int, float etc in C# are struct. It is not far from the fact that they are value types, but it was interesting to know that they are declared as

    public struct Int32 : IComparable, IFormattable, IConvertible, IComparable<int>, IEquatable<int>

    Similar thing for other numeric types. Whereas an enum [System.Enum], though a value type, is declared as an abstract class that derives from System.ValueTypes unlike the int or float. The end result is that enums are value types but i wonder the way they are declared.

    Anyway, the question still remains unresolved - why enums cannot be used as constraints, andjust the specification saying that enums cannot be used as constraints is unsatisfactory.

    I am not sure if there is any other way to resolve my situation.
    Question open to cyber space !!!

    P.S.
    Refer section 25.7 through for the specification on Generic Type Constraints.

    Fooled by the Activator !!!

    It was interesting to know that a custom exception, say an exception class derived from System.ApplicationException, thrown while creating an instance of a type using Activator.CreateInstance does not get caught in its appropriate exception handler, instead gets caught in the global exception handler "catch(Exception ex)", if provided. Any exception raised while creating an instance of the loaded type is wrapped inside a new exception object as InnerException by Activator.CreateInstance.

    I was fooled that there was some problem with the image generation for quite some time, and then very lately inspected the members of the exception caught and found my exception object wrapped as InnerException.

    Now my global exception catch handler catch(Exception ex) has the logic to check if there is any inner exception in ex and inspect if it is of my custom exception type. I am not sure but why cannot the custom exception be thrown as such by the Activator.CreateInstance without wrapping it inside a new Exception object. Would not that be good besides saving a few lines of code ?

    Properties C# 2.0 - Not Elegant Enough !!!

    Prior to .NET 2.0, there wasn't the facility in C# to opt the visibility level for the get and set property or indexers. And i take my comment in my previous post that C# does not provide the facility of having different visibility levels for the get and set accessors. While that is partly correct, it is no more in C# 2.0.

    And obviously it isn't in the easy and elegant way. Take a look at this code snippet:-

    public bool LogToStdError
    {
      get
      {
         return _log2StdError;
      }
      protected set
      {
         _log2StdError = value;
      }
    }


    I do not have to explain the code except there are some restrictions while having different visibility levels for the get/set accessors of a property.

    1. You can provide an explicit visibility either for get or set. Hence the following code will throw an error:-

    public bool LogToStdError
    {
      protected get
      {
         return _log2StdError;
      }
      protected set
      {
         _log2StdError = value;
      }
    }

    2. The visibility thus explicitly specified must be a subset [restrictive than] of the propery declaration. For example, if the property declaration is protected, then the get/set accessor cannot be like say public. So the following code throws an error:-

    protected bool LogToStdError
    {
      get
      {
         return _log2StdError;
      }
      public set
      {
         _log2StdError = value;
      }
    }

    I feel that these restrictions are stupid, and this resulted because of the syntax.  I just thought of some ideas for a bit elegant syntax for the property definition.

    1. The get and set accessors individually have to specify the visibility level.

    bool LogToStdError
    {
      public get
      {
         return _log2StdError;
      }
      property set
      {
         _log2StdError = value;
      }
    }

    2. The property declaration syntax must not bear any visibility level unless the associated get/set accessors do not bear any. For example, in the property definition below, the get/set accessors are public:-

    public bool LogToStdError
    {
      get
      {
         return _log2StdError;
      }
      set
      {
         _log2StdError = value;
      }
    }

    and as per this property definition, the get/set accessors are protected:-

    protected bool LogToStdError
    {
      get
      {
         return _log2StdError;
      }
      set
      {
         _log2StdError = value;
      }
    }

    3. If there are visibility levels specified neither in the property definition nor in the accessors, then the default visibility level as specified for C# [I guess internal] will be applied for the property accessors. Hence the get/set accessors are internal for the following property:-

    bool LogToStdError
    {
      get
      {
         return _log2StdError;
      }
      set
      {
         _log2StdError = value;
      }
    }


    out, ref and InvokeMember !!!

    When I was working on the .NET reflection extravaganza thing that I explained in my previous column, i learnt one another interesting thing, that is about the Type.InvokeMember. How will pass out or ref parameters for the method invoked using Type.InvokeMember ? If you are going to invoke a method with the prototype

    int DoSomething(string someString, int someInt);
    then you would use InvokeMember like this:-
    object obj = someType.InvokeMember("DoSomething", 
            BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
            null,
            this,
            new object[] {"Largest Integer", 1});
    or use some variables in the new object[] {...}. But what do you with the args if DoSomething takes out or ref parameters ?

    int DoSomething(out string someString, ref int someInt);
    Something like this will not work
    string someText = string.Empty;
    int someInt = 0;
    object obj = someType.InvokeMember("DoSomething", 
            BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
            null,
            this,
            new object[] {someText, someInt});
    

    It is tricky.

    object[] args = new object[] { someText, someInt };
    object obj = someType.InvokeMember("DoSomething", 
            BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
            null,
            this,
            args);

    or even suprisingly this works:-

    object[] args = new object[2];
    // or object[] args = new object[] { null, null };
    
    object obj = someType.InvokeMember("DoSomething", 
     BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
     null,
     this,
     args);

    Access the values by indexing args. So declaring the argument object[] as a local variable solves the problem, but I do not understand why this behaviour. May be somebody can explain !!!

    .NET Reflection Extravanganza !!!

    I was involved in this module for the past few weeks and successfully completed it in a very innovative way. Ok, this was the problem. We have a COM server, let us name it Server. I had to write an assembly in C#, let us call it Bridge, that will listen to all of the events fired by the Server and perform an action Action. To keep that Action simple, let us assume we have to log them in the database. But the Server fires hundreds of events, and it is not wise to write up static event handlers for all of them. Also if more events are added in the future, it is possible to support the Bridge.

    So I came up with a different approach with the incredible Reflection in .NET. All of the events fired by the Server, its prototype and other relevant information can be got through reflection, and for each of the event methods, an event sink [event handler] can be generated at runtime. This means I have to create a method at runtime matching the prototype of the event. The dynamic method thus generated runtime has to appended with some method body so as to do the Action, and then has to be registered as the event sink for the corresponding event. So when the event is fired by the Server, the dynamically created event handler is called without any intervention. This is the theme of my solution. This keeps the Bridge unaffected for any event related changes in the Server.

    But achieving this solution and make it work, it was a great and exciting adventure.

    1. I was able to get the event information about the events fired by Server through reflection. I used the following sort of code for generating the dynamic method or the supposedly the dynamic event handler:-

    
    using System;
    using System.Threading;
    using System.Reflection;
    using System.Reflection.Emit;
    
    class TaskDynamicEventHandler
    {
    
        public static void CreateDynamicEventHandler(ref TypeBuilder myTypeBld,
                             string methodName,
                             Type[] eventMethodParameters,
                             Type eventreturnType)
        {
    
            MethodBuilder myMthdBld = myTypeBld.DefineMethod(methodName,
                              MethodAttributes.Public | MethodAttributes.Static,
                              eventreturnType,
                              eventMethodParameters);
    
            ILGenerator ILout = myMthdBld.GetILGenerator();
    
            int numParams = eventMethodParameters.Length;
    
            for (byte x = 0; x < numParams; x++)
            {
                // Load the parameter onto the evaulation stack
                ILout.Emit(OpCodes.Ldarg_S, x);
            }
    
            // Use the above sort of logic to access the event parameter
            // values and then package into a hashtable, and then call
            // a static method HandleEvent in TaskDynamicEventHandler,
            // which takes the hashtable as a parameter. All the code is 
            // generated in IL using ILGenerator.
    
            ILout.Emit(OpCodes.Ret);
        }
    
        public static void Main()
        {
            AppDomain myDomain = Thread.GetDomain();
            AssemblyName asmName = new AssemblyName("DynamicAssembly1");
            AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(asmName,
                           AssemblyBuilderAccess.RunAndSave);
    
            ModuleBuilder myModule = myAsmBuilder.DefineDynamicModule("DynamicModule1",
                                          "MyDynamicAsm.dll");
    
            TypeBuilder myTypeBld = myModule.DefineType("MyDynamicType",
                                           TypeAttributes.Public);
    
            string dynamicMethodName = "DynamicEventHandler";
            CreateDynamicEventHandler(myTypeBld,
                             dynamicMethodName,
                             eventMethodParameters,
                             eventreturnType);        
    
            Type myType = myTypeBld.CreateType();
            
    
            myAsmBuilder.Save("MyDynamicAsm.dll");
        }
    }
    

    The drawback in this approach was that a dynamic assembly+module+type was getting created for each event. This was not efficient enough, and so slightly altered the logic to create the dynamic assembly+module+type once and add the methods [dynamic event handlers] to the dynamic type.

    Though a level of efficieny may have been achieved, it was not elegant enough to be satisfied. The dynamic event handlers [DEH] are all methods of a specific type belonging to a different assembly that is generated at run-time, and these DEH do not belong to the same assembly as the TaskDynamicEventHandler class. The responsibility of the DEHs was to read its parameter name and values at runtime, package them into a hashtable and call a method HandleEvent of TaskDynamicEventHandler, and it is in HandleEvent that the actual job of logging is done. Well, the actual job is not only logging but other things that require access to the memebers of TaskDynamicEventHandler. So the non-elegance here was that HandleEvent was exposed as public static method so that the DEH in the dynamic assembly could call, which lead to the ugliness where HandleEvent was exposed to the outside world from the assembly to which TaskDynamicEventHandler belongs to. So HandleEvent cannot be non-public. But it was required for other reasons to be an instance method.

    2. Here is the most interesting part. The aim was then make the DEH call an instance method of the TaskDynamicEventHandler ie HandleEvent. How do you make a static method call an instance method ? Well, if I have an object reference of the TaskDynamicEventHandler class in the DEH execution, and IF i can load that on to the evaluation stack [using the IL code/ILGenerator], then i call an instance method. That was the pain and it was pretty tricky and interesting that everybody to whomever I explained could not correctly grasp that the 'this' used during the compiled code will not be the same in the runtime IL code of the DEH, and neither can I load an object reference without me creating it or getting it as a parameter. That is all the .NET type security. You will not be given any chance to do reinterpret_cast kind of stuff at all. But you can pass the TaskDynamicEventHandler object reference [this] to the DEH but that beats the goal where the prototype of the DEH will not match the prototpye of its corresponding event and so cannot act as a sink.

    3. Here comes .NET 2.0 for the rescue to a certain extent, and helps us acheive the aim - Efficiency and Elegance. There is a class by name DynamicMethod to dynamically create methods. The beauty of the DynamicMethod is that it is possible to add the dynamic method as member of the current class TaskDynamicEventHandler.

    // returnType - event method's return type
    // parameterTypes - event method's parameter types list
    ArrayList parameterTypes = new ArrayList(parameterTypes);
    parameterTypes.Insert(0, this.GetType());

    DynamicMethod dynamicEventHandler = new DynamicMethod(methodName,
    returnType,
    (Type[])parameterTypes.ToArray(typeof(Type)),
    typeof(TaskDynamicEventHandler));

    Hence the DEH is now a part of the same assembly and class and it can call even non-public methods. Efficiency was well achieved but still elegant was a few feet away. The dynamic method created and added to TaskDynamicEventHandler using DynamicMethod class is a static method and hence cannot access instance methods of TaskDynamicEventHandler, although it can access non-public methods.


    3. Here is the most interesting part. The aim of this iteration is to make the DEH call an instance method of the TaskDynamicEventHandler ie HandleEvent. How do you make a static method call an instance method ? Well, if I have an object reference of the TaskDynamicEventHandler class during the DEH execution, and if i can load that on to the evaluation stack [using the IL code/ILGenerator], then i call an instance method. Things are going to get interesting now. The difference between an instance and static method is that an instance method has the object reference, to which it belongs, as the first parameter while a static method does not. Though syntactically, the object reference is not added, the compiler adds it. So while creating the dynamic method [DEH] for an event, the TaskDynamicEventHandler object reference [this] is added as the first parameter to the event parameter list. This makes the DEH seem to be an instance method. So during runtime, when an event is fired, its corresponding DEH executes, the Lgarg_0 in the IL code represents the object reference it belongs to, and it is the same as that for HandleEvent.

    4. But even now the HandleEvent is public and is vulnerable for improper usage. I made it a virtual method. That is fun, and now it is entirely the user's responsibility to avoid improper usage, and it is upto the user to override HandleEvent to do whatever he wants.

    5. Few minor things- Added Trace.WriteLine in the IL code using ILGenerator for debugging; Added try-catch exception blocks for catching exceptions, but unfortunately does not seem to work.

    All of these approaches until the final efficient and elegant solution took several iterations of revisit and review. I will not able to explain about the difficulties and tough IL debugging experience that I went through trying to make the HandleEvent an instance virtual method, although I will be able to share the joy and knowledge now. It was a great experience !!!

    Non-conventional Window Shapes [I love C#] !!!

    I am not a UI guy. More specifically, I love to work with UIs. I think (only) a UI can give a better picture of the system in a multitasking environment unlike Unix. I do not say I hate Unix. And I do not like to work on UIs ie program on UIs cuz I do not know much. But have always wanted to create a non-conventional window, say an elliptical one. .NET made things like that very easy for guys like me. Look at the code below for creating a ellipitcal window.

    GraphicsPath windowShape = new GraphicsPath();
    windowShape.AddEllipse(0, 0, 320, 200);
    this.Region = new Region(windowShape);

    The GraphicsPath has methods to create wiondows of other shapes too.

    I am not sure but I think it was not this straight forward in the MFC/Win32 programming world. Thanks to C#.NET. I love this 3 lines of code.

    Know where you initialize and Do not forget to uninitialize !!!

    If you have long been programming in C++/COM and then you move to C#.NET, the first difference you can feel is that you got a ctor for the object you create unlike the CoCreateInstance. In the C++/COM world, you generally would have a Initialize method to do the constrcution sort of, paired with Terminate/Uninitialize method. Similar is the case with singleton classes. For singleton classes in C++, you will have public static Instance or GetInstance method to get the only and one instance of the class and then use the initialize method to do the construction. This is certainly advantageous than the ctor facility in .NET, since you will not know when the instance will be initialized without the initialze method. Any call like SingletonClass.GetInstance().SomeMethod may initialize the singleton anywhere and you will not exactly do the initialization during the application startup, which in many cases will lead to application errors after startup.
     
    I do not recommend putting the initialization logic in the ctor, particularly for singletons. The Initialize/Uninitialize method seem to be primitive and kind of from the legacy age but we want code elegance rather than fashion. The pair gives a reasonable intuition and a feel of responsibility to initialize and uninitiailze. Without this simple pair, the object [singleton or any .NET object] gets initialized without control. Also the developers as soon as they enter the .NET world, with the advice from somebody next door, instantly or deliberately forget the memory management and leave everything to GC. But GC can perform the uninitialization required by the business logic.
     
    The Initialize/Uninitialize pair just silently enforces to follow the pattern to initialize at the right place, and most important uninitialize, not giving the risk of remembering about Dispose.
     
    I was forced to write this comment because I was forced to write that code.