C#

Problem Reduction

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.

Article hero image

JINQ

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.

Partial Classes – Java ???

I am really sorry if I tricked you into believing that Java is offering partial class feature. Unfortunately, Java doesn’t. Maybe never will. But I am going to talk about a workaround also presenting the thought process. Hence the length of the post. More ...

.NET for the next generation

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

An Unfair World of Tuples, Anons., var and auto

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

  1. return an instance of a class that holds the values
  2. return a tuple
More ...

Mutating Strings

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

The Secret behind Bjarne and Herb’s Papers on Unified Syntax

A long time back, in one of my posts here1, I had discussed about Extension Methods2 … in C++; sorta! It seems that the grand daddy, Bjarne Stroustoup3, had read my post, and was impressed. So he has published a paper – Call syntax4: x.f(y) vs. f(x,y). Good thing except I don’t like the idea of assuming x.f(y) for f(x, y) while the reverse is the actual idea of extension methods. You will know when you read his paper. It seems the commander, Herb Sutter5, also was impressed with my post. Not only that he too doesn’t seem to like the x.f(y) for f(x, y) idea. Great men think alike. LOL! So he published his paper – Unified Syntax6. How is that? More ...

A Simple Tree List View

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.

Offering __FILE__ and __LINE__ for C# !!!

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

OrderedThreadPool – Bug Fix !!!

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…

More ...

Unique Id Generation !!!

A short while I was engaged in a little project where I had to interact with a third party service provider who required a (30 length) unique id as part of the transaction. I am little dumb and am used to GUIDs for a long time when it comes to unique ids. But GUIDs are more than 30 in length. I was trying out some stupid ways like stripping out the trail part of the GUID to make 30 length unique but my intuition wasn’t convinced about the tricks I was working out. More ...

Android meets .NET

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

Anonymous Classes vs Delegates !!!

I am not a java programmer. By that, I do not mean I am against Java. As a programmer by profession and passion, I try to learn things along the way. That includes a little of bit of Java. I should say that my proper encounter, so to say, with Java is a simple application that I am trying out with Android. There might be some hard core differences and/or limitations in the Android version of Java. But I am almost certain that I am using only primary level features of Java. More ...

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.

More ...

Invoking methods with Out and Ref (Part 2) !!!

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

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

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

More ...

sizeof vs Marshal.SizeOf !!!

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.

More ...

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

More ...

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.

More ...

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

Settling Casting Restrictions

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.

More ...

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

More ...

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.

More ...

Extension Methods – A Polished C++ Feature

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

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

More ...

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

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