Wrong compiler warning? Or Not?

This piece of code results in a warning. 1: class Test 2: { 3: public static void Main() 4: { 5: object obj = "Senthil"; 6: string myName = "Senthil"; 7: Console.WriteLine(obj == myName); 8: } 9: } The compiler says “warning CS0252: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type ‘string’” on line 7. The compiler is right; it has no way of knowing that obj is actually a string. It infers the static type of obj to be System.Object, and if you’ve done any programming in C# at all, you’ll … Continue reading Wrong compiler warning? Or Not?

Anonymous methods as event handlers – Part 2

The previous post discussed having anonymous methods as event handlers and ended with a question – why doesn’t unsubscription work while subscription works out alright? Vivek got the answer spot on – the way the C# compiler handles and translates anonymous methods is the reason. Here’s the code involved. 1: public void Initialize() 2: { 3: control.KeyPressed += IfEnabledThenDo(control_KeyPressed); 4: control.MouseMoved += IfEnabledThenDo(control_MouseMoved); 5: } 6:  7: public void Destroy() 8: { 9: control.KeyPressed -= IfEnabledThenDo(control_KeyPressed); 10: control.MouseMoved -= IfEnabledThenDo(control_MouseMoved); 11: } 12:  13: public EventHandler<Control.ControlEventArgs> IfEnabledThenDo(EventHandler<Control.ControlEventArgs> actualAction) 14: { 15: return (sender, args) => { if (args.Control.Enabled) actualAction(sender, args); … Continue reading Anonymous methods as event handlers – Part 2

Anonymous methods as event handlers – Part 1

The syntactic sugar offered by anonymous methods makes them great candidates for writing event handlers; together with smart type inference, they reduce the amount of code written by an order of magnitude. And that’s without considering the power offered by closures. With event handlers, closures allow you to kind of “stuff” extra parameters into the handler, without changing the actual number of formal parameters. This blog post shows a situation where an anonymous method acting as an event handler makes code simpler, and then goes on to show a gotcha with un-subscription and anonymous methods. Here’s a simple Control class … Continue reading Anonymous methods as event handlers – Part 1

Remoting IEnumerables

You’re writing this really cool and innovative class to calculate the first hundred thousand natural numbers. You think about the API, and you realize that returning an array of the numbers a) might take a long time to complete, and b) is going to cause memory usage to spike up like mad. So you decide to stream them instead, returning an IEnumerable<T> instance instead of an array. Being a crack C# developer, you use the incredibly powerful yield keyword, rather than rolling your own implementation of the IEnumerable<T> interface. 1: class MyCoolMathEngine 2: { 3: public IEnumerable<int> GetFirstHundredThousandNaturalNumbers() 4: { … Continue reading Remoting IEnumerables

Overload resolution and null

My colleague Soundar discovered this rather interesting behavior. 1: class Test 2: { 3: public static void Main() 4: { 5: Test test = null; 6: 7: Console.WriteLine("{0}", test); 8: Console.WriteLine("{0}", null); 9: } 10: } If you run this code, you’ll find that while line 7 prints an empty line, line 8 causes an ArgumentNullException. Note that the test reference is also null, so it should certainly surprise you that the two lines result in different behavior at runtime. It certainly surprised me enough to make me dig deeper into the reason for the difference. I reasoned that given … Continue reading Overload resolution and null

Volatile and local

If you’ve done any multithreading programming at all, you must be aware of the volatile modifier. When a field is marked volatile, it tells 1. the JIT compiler that it can’t hoist the field because it may be modified by multiple threads 2. the CLR that the field must be read to and written from with acquire and release semantics. Given what you’ve read above, the post’s title doesn’t make sense. A local variable, by definition, cannot be accessed from multiple threads. An object referred to by a local variable can be shared among threads, but never the variable itself. … Continue reading Volatile and local

Mutating value types – Part 1

Take a look at the following short snippet of code. 1: using System; 2: 3: struct S 4: { 5: public int X; 6: } 7: 8: class C 9: { 10: /* More code here */ 11: } 12: 13: class Test 14: { 15: public static void Main() 16: { 17: C c = new C(); 18: c.S.X = 1; 19: } 20: } Without knowing the type definition of C, can you tell whether the code will compile, much less work? Turns out that you can’t. It depends on whether the S in c.S is defined as … Continue reading Mutating value types – Part 1

Confusion++

I’ll bet a hundred bucks that any entry level C++ interview or exam will somehow drift into questions about the pre and post increment operators. It’s almost become a canonical, rite of passage sort of thing. Now using the operators is one thing, overloading them for your own types is another. In C++, you write something like class X { int val; public: X() : val(0){ } X operator++() { val++; return *this; } X operator++(int) { X pX = *this; val++; return pX; }; int Value() { return val; } }; Fairly straightforward stuff – C++ uses the int … Continue reading Confusion++

Writing your own SkypeBot

If you use Skype, do you know that you can program against it? Head over to developer.skype.com if you’re interested. There’s a COM API, one for Java and even one for Python. Just to show how easy it is, we’ll write a bot in .NET that will simply echo whatever is sent to it. You first need to download Skype4COM, a COM library provided by Skype developers to control Skype. Create a WinForms application in your favorite version of Visual Studio (>= 2005), and in the default Form class, paste the following piece of code public partial class MainForm : … Continue reading Writing your own SkypeBot