Digging up stash is one of the best pass times. You know you never know what you will find. I had an article written quite some time back but had not posted it anywhere. Not sure why. I posted it at CodeProject β A Simple Tree List View.
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:-
More ...
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 -0
in hand, 1
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.
More ...
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):-
More ...
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:-
There are two facilities in C# to determine the size of a type β sizeof
operator andMarshal.SizeOf
method. Let us discuss what they offer and how they differ.
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 not be writing this post.
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).
More ...
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.
Article co-authored with Sanjeev, and published on CodeProject
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 and the way to generate the message is of our interest now. So we are in need of a logger class that can behave transparent to the logging destination. That should not be a problem, it would be fun to design that.
More ...
This article was co-authored with Sanjeev, and published on CodeProject
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 and the way to generate the message is of our interest now. So we are in need of a logger class that can behave transparent to the logging destination. That should not be a problem, it would be fun to design that.
More ...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.
This is about a killer bug identified by our chief software engineer in our application. 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.
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. More ...
Remember the Casting Restrictions we discussed a while back, let us settle that now. So we have some code like this:
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.
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.
More ...
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!).
More ...
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.
More ...
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:-
More ...
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();
}
}
}
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 URL to enjoy the gadgets.:
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. More ...
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. More ...
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 enum
s cannot used as generic constraints. I learnt the following from my investigation:
Following is an excerpt from the C# language specification for generic constraints
A class-type constraint must satisfy the following rules:
The type must be a class type.
The type must not be sealed.
The type must not be one of the following types: System.Array
, System.Delegate
, System.Enum
, or System.ValueType
.
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. More ...
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
.
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:-
More ...
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.
More ...
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 ?
More ...