Logging Experiences

An example for C# dynamic in action

Posted in C#, Programming, Tips and Tricks by Sina Iravanian on July 23, 2012

Recently I was involved with enabling validation for a Windows Forms form containing several pages shown through a tree view. There were one user control defined for each page, therefore whenever a node in tree-view got activated, an instance of that user-control were shown. The user-controls did not have a common user-defined parent base-class or interface. The author of the existing code had defined a Save method in each control separately which performed updating data with values entered in the forms.

First, I changed all void Save() methods to bool Save(), and performed the validation stuff in each control separately. Then in the parent form, I created an array of Controls, so that I could loop through them, and call their Save method. But wait, Save is not inherited from any base-class or interface, so there’s no polymorphism at hand. How can I call them through references of type Control?

Well honestly, the best solution would be adding a new interface to the project, say ISavableControl or something, add the Save method to it, and let the controls implement that interface. But I wanted to make a quick fix to the problem without adding new files and types to the code. Here C#’s dynamic comes into action.

Using dynamic keyword, one postpones binding methods, properties, and fields to run-time. In our scenario we know that the user-controls each have a method called Save, which is not derived from a parent. Without dynamic, I would need to have a reference explicitly from each user control’s type, and I would have to call them one by one, as in:

bool succeeded = false;
succeeded = userControl1.Save();
succeeded = succeeded || userControl2.Save();
succeeded = succeeded || userControl3.Save();
// ...
succeeded = succeeded || userControln.Save();

However using dynamic keyword, life gets a lot easier:

// objects are not inherited from a base class or interface,
// therefore we cannot call Save using polymorphism
bool succeeded = false;
foreach(var ctrl in controlsArray)
    dynamic dynCtrl = ctrl;
    succeeded = succeeded || dynCtrl.Save();

// do something with the value of succeeded

Take care that binding the Save methods to controls happen at runtime. Therefore if a control does not implement a Save method, or if another one misspells Save, as say Svae, you will get no hints at compile time. So, try to avoid this style of coding, unless you have good reasons for doing so.

Tagged with: , ,

Code Snippet: Mean, Variance, and Standard Deviation Methods

Posted in C#, Programming, Snippets by Sina Iravanian on May 15, 2011

The methods to calculate mean, variance, and standard deviation of a vector of values. These are put here for easy reference, so that I do not need to rewrite them again.

A Helper Method for Performing K-Fold Cross Validation

Posted in C#, Programming, Snippets by Sina Iravanian on May 15, 2011

The following method is a utility method for creating the K divisions upon which one is going to perform the K-fold cross validation operation. The input of the method is the length of the training data, and the number K. The output says which indices of the training-data is to be put in each division.

Tagged with: ,

Code Snippet: Trimming Strings of White-space and control characters

Posted in C#, Programming, Snippets by Sina Iravanian on March 2, 2011

The following method trims the given string of both white-space characters and control characters, and its rather fast!

Tagged with: , ,

Tips and Tricks: Making Windows Forms Size to Their Content

Posted in C#, Programming, Tips and Tricks by Sina Iravanian on August 15, 2010

Windows In WPF can make use of a property which makes the window to automatically adjust its own size to fit its content. The related property in WPF is SizeToContent which can be set to Manual (the default), Width, Height and WidthAndHeight. The last item makes the window shrink or grow so that it will fit its content.

The same effect can be made in Windows Forms using the AutoSize and AutoSizeMode properties of the form. Simply set AutoSize to true and also do not forget to set AutoSizeMode to GrowAndShrink. This effect is not visualized during design.

Tagged with: ,

Code Snippet: Determining how two intervals overlap

Posted in C#, Programming, Snippets by Sina Iravanian on August 9, 2010

The following pieces of code help you figure out how two intervals overlap, and provides tools to represent them in a way that is useful for debugging purposes. This job is quite easy to accomplish, but since it is written too frequently each time from scratch, I have put them in this gist.

The IntervalOverlapKinds.cs file defines the IntervalOverlapKinds enumeration. The interval detection is carried out in the static methods of the IntervalOverlap class.

Code Snippet: Representing strings with all their characters visible

Posted in C#, Programming, Snippets by Sina Iravanian on August 8, 2010

This piece of code is useful if you intend to work on a string processing algorithm. There are times, that you need to see the real content of a string while showing them in a windows form, console, and so on. This little method may help:

Code Snippet: Searching and Highlighting a token or string in a RichTextBox

Posted in C#, Programming, Snippets by Sina Iravanian on August 8, 2010

Suppose that you intend to find a string or a token (i.e., whole word, instead of a substring) and change their color in some RichTextBox. The following code snippets will help. The FindStringAndSetColor method looks for instances of an arbitrary string in the contents of the RichTextBox, while the FindTokenAndSetColor method looks for whole words (tokens).

Tagged with: , ,

One reason to prefer readonly to const in C#

Posted in C#, Programming, Tips and Tricks by Sina Iravanian on April 21, 2010

First off, let’s talk about what’s going on in C# compiler when you use const or readonly in your field definitions. The const qualifier can be used with primitive data types, and strings only. When used, the value assigned to a const field, is inserted directly in all its references in the generated IL code. This is true about other assemblies too. Other assemblies that refer to that const field, are compiled as if they have used directly the value itself. This can be the source of problem that I’m going to talk about soon. Readonly fields are run-time constants. They occupy some place in memory, and references to them are resolved in run-time, as if we have referred to an ordinary variable. Actually they are variables that resemble constants.

Imagine that you have created and released a project to public. Your project contains several assemblies in form of .dll files. They make use of some constant value in one of the .dll files, e.g., SomeLibrary.dll stores a constant value in one of its classes, e.g.,

public class Options
   public const int NetworkTimeout = 2000; 

You realize that the value assigned to NetworkTimeout is less than expected, so you decide to update SomeLibrary.dll files in all your customer machines with a new one in which NetworkTimeout is set to 3000. But it will not work. Because all references to NetworkTimeout in other assemblies have been replaced with the constant 2000, and the new value will not be fetched any more. In this case the problem will be solved only when all other assemblies are rebuilt. No other update scenarios will do.

But if we have used readonly instead of const the problem would have been solved with updating SomeLibrary.dll only.

public class Options
    public static readonly int NetworkTimeout = 2000;

The static modifier has been added only to make the two codes above compatible. Note that all const fields are also static, but readonly fields can be either static or an instance field.

Tagged with: ,

YAXLib 2.0 is Released

Posted in C#, Programming by Sina Iravanian on April 17, 2010

I am finally finished with YAXLib 2.0. The CodeProject article is available here [+], and the source code is available from here [+].

See the ChangeLog file to see what is new, and read the CodeProject article and run the demo application to see what are the capabilities of the library. In short I can name these:

  • Structure freely the XML Result.
  • Serialize all known generic and non-generic collection classes in System.Collections, and System.Collections.Generic
  • Serialize single-dimensional, multi-dimensional, and jagged arrays.
  • Support for specifying path-like serialization addresses, e.g., "elem1/elem2/elem3", and "../elem1", and "./elem1".
  • Specify aliases for enums.
  • Choose the fields to serialize (public, or non-public properties, or member variables).
  • Serialize and deserialize objects through a reference to their base-class or interface.
  • Support for multi-stage deserialization,
  • and more …

The most joyful implementation parts of this library was adding the support for serialization and deserialization of multi-dimensional, and jagged arrays, and also the support for serialization and deserialization of objects through a reference to their base-class or interface.

Please let me know your bug reports and feature requests.

Tagged with: , ,