Skip to main content

Posts

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

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 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, IComp...

First Google Gadget(s) !!!

I did some cool stuff here with google. I wrote my first "Hello World" sort of google gadget. It claims no rewards but just was fun. Since I am a novice in html and javascript sort of things, this gadget is pretty simple. Use the following URLs http://vivekragunathan.googlepages.com/Pirate.XML http://VivekRagunathan.GooglePages.com/Clock.XML to enjoy the gadgets.

Overloading......A Matter Of Taste !!!

This was a pretty interesting discussion about method overloading in the managed world. As the discussion says that the overloading is a matter of taste. It seems that the method overloading in the managed world, indeed, is a matter of taste. Sad BUT True !!! But on the contrary, it must have been a [strict] rule. Overloading might be exhibited differently by each language in the unmanaged world. But as far as .NET goes, it must have been made a standard specification. Pardon me, if there is one. As it was pointed out in the discussion, how do we define the behaviour in the case where we derive classes across assemblies developed in another .NET language ? As far traditional C++ goes, the overloaded method resolution starts from the derived but does not have strict type checking eg. for numeric types]. And the point to note is that only the method in the derived class with the exact prototype as the base is considered the overload. Ofcourse, C++ is not as much type safe as C#. This is...

Follow the trail.......Join the Concurrency Revolution !!!

I could not stop writing this post after I read this article by Herb Sutter. The article is just a casual technical discussion but very encouraging that a person requires at the right time - the time when he is a student. Even after several years after my college, I have been trying to keep myself a student and I got a right encouragement to join the Concurrency revolution. Thanks to Herb Sutter. As Albert Einstein, Robert Goddard, and Wernher von Braun walked the trail of Galileo and Newton , I will to walk the trail of some of the contemporary people like Sutter, Stroustoup, Don Box, Richter and others.

The New Looking Post !!!

I am very much fond of tools, updates and stuff. So I keep updating my softwares and hear/learn about new tools etc. I am excited about the new spaces - Live Spaces. Looks much better than before. I thought I would write something about the new spaces. Please 'spaces guys', make the arranging the boxes on the home page a bit easier and intelligent. That is a feature request. Otherwise the default skin/theme is cool and professional. Old themes are still old and not much appealing. Anyway, i write the post just to say i love it. And talking about tools and softwares, i heard this news about Microsoft acquiring the SysInternals tools. And probably, Microsoft might be shipping the tools like Debug View , Process Explorer , RegMon etc with the Windows SDK. Me not sure of that, better read what Tom Archer said.

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

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

Singularity - Safety & Speed !!!

I read about this interesting thing somewhere in MSDN. There are two types of programming or programming languages. The good old C/C++ kind called the unsafe programming languages, and the other is the safe programming type which we realised very much after advent of Java/C#. And there has always been debate about safety and speed. And neither of the two has won. So Microsoft is doing a research on a new operating system called Singularity which is written in a safe programming language [C#]. Although there are parts in the OS, especially the kernel, that uses unsafe code, it stills uses the safe C#. So in the Singularity environment, every program that runs is safe. And the environment as such is reinventing from the hardware layers up and above. Any process in singularity will not be as huge as its counterpart in the unsafe world. It will start with very minimal image and bring up things as when required. But also there was some thing that i read but could not understand exactly. It ...