Problem Reduction is what I call when a given problem can be expressed in terms of or solved using a solution to an alternate problem. Take for instance, the word distance problem: Find the shortest distance between two words in a given set of words.
JINQ (Java INtegrated Query) is an ultra minimalistic library inspired from and mimicking the .NET LINQ. While LINQ is a language level construct, JINQ is composed of types - classes and methods, but to the same effect.
I came across LeanPub 1 a few months back. I believe it was through hanselman2 β blog, video or something. I liked LeanPub instantly because of a couple of reasons.
I hadnβt written/published any lengthy material in a long time except the C+/CLI Primer on CodeProject4. Why not publish same, I thought, and actually published5. I wasnβt even expecting any response from anyone since the material was on C++/CLI, a language that gave me the impression that I was the only one using it at the time I published on CodeProject. π I am really impressed that the material topped more than 50 downloads in about three months since it was published. Heck, a couple of them even paid despite the fact that the material is free. Not only am I humbled by this encouraging gesture but I am also convinced that C++/CLI is still being pursued and will continue to live β production, academic or as a pet language. Go grab your copy of the booklet β C++/CLI Primer. Itβs free!
More ...It was about a decade ago when Visual Studio .NET 2002 was launched. Having worked with Visual Studio 6 until then, the new interface was refreshing and powerful along with .NET and the suite of languages, tools and technologies. If you were there, you would have felt times were changing. Beyond the cool and modern interface, Visual Studio .NET 2002 had a lot more to offerβ compared to Visual Studio 6 ββ.NET. It was an exciting time for me back then. More ...
It all began when I wanted to return more than one value from one of the methods. Although my attempts ended futile, it was fun exploring and musing how things could have been.
There are at least a couple of options to return multiple values from a method:-
Today, we question our beliefs! Is string really immutable?
string message = "Hello World!";
Console.WriteLine(message); // Prints "Hello World!"
unsafe {
int length = message.Length;
fixed (char *p = message) {
for (int index = 0; index < length; ++index) {
*(p + index) = '?';
}
}
}
Console.WriteLine(message); // Prints what? See for yourself!
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.
Not the same way but we could say better.
Visual Studio 2012, another power packed release of Visual Studio, among a lot of other powerful fancy language features, offers the ability to deduce the method caller details at compile time.
C++ offered the compiler defined macros FILE and LINE (and DATE and TIME), which are primarily intended for diagnostic purposes in a program, whereby the caller information is captured and logged. For instance, using LINE would be replaced with the exact line number in the file where this macro has been used. That sometimes beats the purpose and doesnβt gives us what we actually expect. Letβs see.
More ...
Hugh pointed out a bug in the OrderedThreadPool.
I think there is a small window for error in the OrderedThreadPool class. Basically, if an item of work is queued, then a worker thread runs, takes the item off the queue and is about to call wcb(state)
β but at that instant is (say) context switched. Then another item gets queued and another worker thread runs and dequeues the item and then again is about to call wcb(state)
. There is scope here for the two operations to run concurrently or even out of orderβ¦
It is always fun to program in C# (besides C++). If so, how would I feel if I was able to program in C# on Android? You may be wondering what in the world I am talking about. Android development environment is all Java and open source stuff. How could this Microsoft thing fit onto it? Well, it seems that some clever guys1 had huddled up and ported Mono for Android, developed .NET libraries for the Android SDK, and also supplemented it with a Mono for Android project template in Visual Studio. Thus we relish writing C# code for Android. More ...
void SomeMethod(int x, double y) {
// some code
...
new Thread(ThreadFunc).Start();
}
What do you think about the code above?
Some may say nothing seems to be wrong. Some may say there is not enough information to comment. A few may say that it is awful to spin off a thread like that (the last line of the method), and that there is a probability for the thread to be garbage collected at an unexpected point of execution. That is something interesting to discuss about.
More ...
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.
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 ...
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.
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 ...
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 ...
Extension Methods 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
.
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 ...
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 ...
Over the past few weeks, I have been involved with this module that got the best of both worlds - .NET and I, π.
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 to 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 (ever) added in the future, the Bridge should be able to support it without code changes.
The twist in the game was that this was a brown + green field development project. That demanded a wise solution - learn from the past and better the future.
More ...