Monday, June 14, 2010

Anonymous class in C#

I find it very annoying that I can't create an anonymous class that implements an interface, or includes a method. Actually the only things that anonymous class can have are properties.

Many of people use 'using' statement as a fast way to deal with IDisposable objects, but they forget that it is also useful to quickly create a block of code that is, in some way, isolated from the rest. Some people use it instead of begin/end block, and in some way I agree with those people. If I know that I am doing some operations that won't be useful later on in my function I can put them into a block and release them at the end. I know that I can create a separate method for it, but sometimes putting something in one method is more readable and understandable then decomposition. From the other point of view, when majority of people see using statement they think about IDisposable interface, and they correlate IDisposable interface with unmanaged code. Unfortunately unmanaged code is not the only case to use IDisposable interface and to manually manage the memory management, but I will live this subject for a separate discussion, and return to the main subject. Abstract classes would be an excellent choice for some ideas that I run into during my work. Sometimes I just want to create a temporary container for a short period of time and later on get rid of it, and free some memory that was used during that object modification. Unfortunately because I cannot implement an interface in an abstract class I cannot use it in a usage statement.

No comments: