Skip to main content

Posts

Guess Who?

You may not know the guy in black; but you sure should be knowing the guy in green. Don't know him ? I am not a patron of his philosophies against planned design. But he sure is a great guy with lots of good ideas. It was nice having an hour long chat with him.

Invoking methods with out and ref - Finale !!!

Alright, it is a long wait. And I am going to keep it short. Recap of the problem: Why did the ref variable in SomeMethod not get the expected result ( DayOfWeek.Friday ) when called from a different thread? Boxing. Yes, that is the culprit. Sometimes, it is subtle to note. DayOfWeek is an enum - a value type. When the method is called from a different thread, we put the argument (arg3) in an object array, and that's where the value gets boxed. So we happen to assign the resultant value to the boxed value. So how do resolve the issue? Simple.......assign the value back from the object array to the ref variable. int SomeMethod(string arg1, string arg2, ref DayOfWeek arg3) { if (Dispatcher.CheckAccess()) { var funcDelegate = (Func<string, string, DayOfWeek, int>)SomeMethod; var args = new object[] { arg1, arg2, arg3 }; int retVal = Dispatcher.Invoke(funcDelegate, args); arg3 = ...

Invoking methods with Out and Ref !!!

Straight to code..... int SomeMethod(string arg1, string arg2, ref DayOfWeek arg3) { // Wildest implementation! } The above method had to be executed on its dispatcher thread. So let unravel a bit of the wildest implementation above. int SomeMethod(string arg1, string arg2, ref DayOfWeek arg3) { if (Disptacher.CheckAccess()) { var funcDelegate = (Func<string, string, DayOfWeek, int>)SomeMthod; return Dispatcher.Invoke(funcDelegate, arg1, arg2, ref arg3); } // Wilder implementation!! } Before you say anything, yes, the compiler spat the following errors:- Error 1 No overload for 'SomeMethod' matches delegate 'System.Func<string,string,DayOfWeek,int> Error 2 The best overloaded method match for 'System.Windows.Threading.Dispatcher.Invoke(System.Delegate, params object[])' has some invalid arguments Error 3 Argument '4': cannot convert from 'ref System....

Thinking Currying !!!

Currying is a mathematical concept based on lambda calculus. It is a technique of operating on a function (taking multiple arguments) by splitting and capable of chaining into a series of single argument functions. It is very similar to what a human would attempt to do on paper. For example, if you have to add numbers 1 through 10, what would you do? Class II mathematics....zero in hand, one in the mind, add 0 and 1, so 1 in the mind, then 2 in the hand, ...up to 10. So we compute the addition with one argument at a time. In the programming world, it is realized by transforming a n-arguments function into a (n-1) arguments function, which takes the remaining one argument. This transformation when applied recursively on each of the single argument functions is the chaining of single argument functions that I discussed earlier. Needless to say, currying is a gift of the functional programming world. In simple words, functional programming is about building functions from other functio...

Quiz - (Journey through templates, SFINAE and specialization) !!!

template<typename A, typename B> class TClass { public: TClass() { } // Overload #1 public: std::string SomeMethod(A a, B b) { std::ostringstream ostr; ostr << a << "-" << b; return ostr.str(); } // Overload #2 public: std::string SomeMethod(B b, A a) { std::ostringstream ostr; ostr << b << "-" << a; return ostr.str(); } }; So that is a template class with SomeMethod overloads. Why would somebody write such a class? Imagine it is an adder class, and the method overloads could used to add with parameters specified in either order. Following is the way one could use the above (based on the adder example):- int i = 45; double d = 12.3f; TClass<int, float> t1; const std::string idText = t1.SomeMethod(i, d); // This calls Overload #1 const std::string diText = t2.SomeMethod(d, i); // T...

Missing MI !!!

We all know C# does not offer multiple inheritance but offers arguments that programmers can live without it. It is true in almost all cases, especially all cat and animal or employee and manager projects. I have seen a few cases where if C# offered multiple inheritance, the solution would have been natural, elegant and succinct. Imagine that I have a component (UI, non-UI, doesn't matter). You can make calls into the component, which does some interesting work for you. Imagine that the component takes an interface IComponentCallback to notify its parent. So I would do is have my parent class derive from IComponentCallback interface and pass this to the component. The code would look something like this:- interface IComponentCallback { void Callback1(); bool Callback2(); void Callback3(int old, int new); } class SomeComponent { // The parent on whom callbacks are made private IComponentCallback _parent = null; public SomeCompoent(IComponentCallback cmpCal...

sizeof vs Marshal.SizeOf !!!

There are two facilities in C# to determine the size of a type - sizeof operator and Marshal.SizeOf method. Let me discuss what they offer and how they differ. Pardon me if I happen to ramble a bit. Before we settle the difference between sizeof and Marshal.SizeOf , let us discuss why would we want to compute the size of a variable or type. Other than academic, one typical reason to know the size of a type (in a production code) would be allocate memory for an array of items; typically done while using malloc . Unlike in C++ (or unmanaged world), computing the size of a type definitely has no such use in C# (managed world). Within the managed application, size does not matter; since there are types provided by the CLR for creating\managing fixed size and variable size (typed) arrays. And as per MSDN, the size cannot be computed accurately. Does that mean we don't need to compute the size of a type at all when working in the CLR world? Obviously no, else I would ...

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 { pr...

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 SomeMetho...

Type Safe Logger

Sanjeev and I have published an article - Type Safe Logger For C++ - at CodeProject. Every bit of work is tiresome or little ugly in C++. So is logging - writing application diagnostics to console, file etc. The printf style of outputting diagnostics is primitive and not type safe. The std::cout is type safe but does not have a format specification. Besides that, printf and std::cout know to write only to the console. So we need a logging mechanism that provides a format specification, is type safe and log destination transparent. So we came up with this new Logger to make C++ programmers happy. Following is a short introduction excerpt of the article:- Every application logs a whole bunch of diagnostic messages, primarily for (production) debugging, to the console or the standard error device or to files. There are so many other destinations where the logs can be written to. Irrespective of the destination that each application must be able to configure, the diagnostic log message a...

Simple Array Class For C++

This is a simple array like class for C++, which can be used as a safe wrapper for accessing a block of memory pointed by a bare pointer. #pragma once template<typename T> class Array { private: T* _tPtr; private: size_t _length; private: bool _isOwner; public: Array(size_t length, bool isOwner = true) : _isOwner(isOwner) { _length = length; _tPtr = new T[length]; } public: Array(T* tPtr, size_t numItems, bool isOwner = true) : _isOwner(isOwner) { if (NULL == tPtr) { throw std::exception("Specified T* pointer is NULL."); } this->_length = numItems; this->_tPtr = tPtr; } public: template<typename TSTLContainerType> Array(const TSTLContainerType& stlContainer, bool isOwner) : _isOwner(isOwner) { _length = stlContainer.size(); _tPtr = new T[_length]; int ind...

Passing CComPtr By Value !!!

This is about a killer bug identified by our chief software engineer in our software. What was devised for ease of use and write smart code ended up in this killer defect due to improper perception. Ok, let us go! CComPtr is a template class in ATL designed to wrap the discrete functionality of COM object management - AddRef and Release. Technically it is a smart pointer for a COM object. void SomeMethod() { CComPtr siPtr; HRESULT hr = siPtr.CoCreateInstance(CLSID_SomeComponent); siPtr->MethodOne(20, L"Hello"); } Without CComPtr, the code wouldn't be as elegant as above. The code would be spilled with AddRef and Release. Besides, writing code to Release after use under any circumstance is either hard or ugly. CComPtr automatically takes care of releasing in its destructor just like std::auto_ptr . As a C++ programmer, we must be able to appreciate the inevitability of the destructor and its immense use in writing smart code. However there is a difference...

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 th...

Settling Casting Restrictions !!!

Remember the Casting Restrictions we discussed a while back, let us settle that now. So we have some code like this: int i = 100; object obj = i; long l = (long)obj; And an invalid cast exception while casting 'obj' to long. It is obvious that we are not changing the value held by obj, but just reading it. Then why restrict such casting. Let us disassemble and see what we got. .locals init ( [0] int32 i, [1] object obj, [2] int64 l) L_0000: nop L_0001: ldc.i4.s 100 L_0003: stloc.0 L_0004: ldloc.0 L_0005: box int32 L_000a: stloc.1 L_000b: ldloc.1 L_000c: unbox.any int64 L_0011: stloc.2 L_0012: ret Oh, there we see something interesting - unbox. So the C# compiler uses the unbox instruction to retrieve the value from obj while casting; it does not use Convert . ToInt64 or similar mechanism. That is why the exception was thrown. From MSDN: Unboxing is an explicit conversion from the type object to a value type o...

The WD Anti-Propaganda Campaign !!!

Thanks to the internet. If nobody else bothers or understands what loss of data means, you can shout it aloud here. I lost 500GB of data - every moment of my personal and professional life captured in bits and bytes. It is a Western Digital Premium Edition external hard disk (USB/Firewire). I bought it despite my friend warning of bad sectors and hardware issues that WD is known to have. As with any story, one fine morning, I was copying some songs, pictures from my pen drive to the hard disk. All of a sudden, the hard disk and my laptop hung up. I restarted the system thinking I would make fresh start. But to my dismay, all my drives on the hard disk had vanished like dust. I tried connecting and reconnecting a few times, the drives showed up once or twice like a sick man's last few breadths. The other similar incident was the hard disk crash at my office last month. It was also a WD 160GB hard disk (IDE). And it took with it more than 5 years of email storage, project documents, ...

Casting Restrictions ???

We all know that the runtime can detect the actual type of a System.Object instance. The primitive data types provided by the runtime are compatible with one another for casting (assuming that we do not truncate the values). So if I have an int, it can be cast to long or ulong. All that is fine. Watch this:- interface IAppDataTypeBase { // Other methods GetValue(); } Since IAppDataTypeBase represents the mother of all types of data in my application, I have made GetValue to return the value as object (I could have used generics, that is for another day!). IAppDataTypeBase longType = GetLongInstanceFromSomeWhere(); int i = (int)longType.GetValue(); So are we discussing any problems here? Yes, we are. The problem is that the value returned by GetValue - System.Object - despite being inherently long cannot be cast to an int. It would result in an 'Specified cast is invalid' exception. If an object is one of the primitive types, it can only be cast to its actual type. In th...

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 obje...

Extension Methods - A Polished C++ Feature !!!

Extension Method is an excellent feature in C# 3.0. It is a mechanism by which new methods can be exposed from an existing type (interface or class) without directly adding the method to the type. Why do we need extension methods anyway ? Ok, that is the big story of lamba and LINQ. But from a conceptual standpoint, the extension methods establish a mechanism to extend the public interface of a type. The compiler is smart enough to make the method a part of the public interface of the type. Yeah, that is what it does, and the intellisense is very cool in making us believe that. It is cleaner and easier (for the library developers and for us programmers even) to add extra functionality (methods) not provided in the type. That is the intent. And we know that was exercised extravagantly in LINQ. The IEnumerable was extended with a whole lot set of methods to aid the LINQ design. Remember the Where, Select etc methods on IEnumerable. An example code snippet is worth a thousand ...

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 req...

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 resear...