static vs dynamic vs strong vs weak vs duck typing

posted by alexis reigel on march 19, 2012

Here’s my take at clearing up the confusion about the most common type systems used in programming.

I often hear how static and strong typing are used as synonyms. These two are however quite different systems. The same applies to dynamic and weak typing. For instance, a programming language can be both dynamically and strongly typed, but not dynamically and statically. Ruby is an example of a dynamically and strongly typed language.
Ok, I guess now it’s the time to elaborate.

static vs dynamic

  // example in c#

  string s = "asdf";
  # example in ruby

  s = "asdf"

strong vs weak

  # example in ruby

  "1" + 1 # TypeError
  // example in javascript

  "1" + 1 // "11"

duck typing

Duck typing is a style of dynamic typing.With duck typing, the set of methods and properties determine the valid semantics of a class, instead of inheritance from a specific class or implementation of an interface.
“When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.”
This means that we actually don’t care if the class we’re using is actually of a certain type, as long as it provides the methods or properties we’re interested in.
The term duck typing comes from python, but ruby is also very known for this behaviour.

DataGridView with an object data source

posted by alexis reigel on september 04, 2010

For my Batch Replacer I am using a DataGridView with an object data source, meaning that I have a collection class that holds the data to be displayed. At first that class inherited from a usual List<T>, which led to the problem that the data binding wasn’t two-way. As soon as I bound data to the DataGridView, it wasn’t possible to add any new rows to it in my user interface. After some research I found out that instead of using a normal List&lt;T&gt; I was supposed to use a BindingList<T>. Using that the binding is two-way, and the user interface is normally editable and new rows can be added. Also, of course, all modifications done in the user interface are reflected in the object (meaning e.g. that when a new row is added, the object data source contains a corresponding entry).

nullable average in linq

posted by alexis reigel on october 12, 2008

The following code is one possibility (there may be more elegant solutions to this) to handle a nullable average from a linq query. The problem arises when the linq query does not return a result, thus the average being null. If you don’t use a nullable type, you’ll get an exception. To get a nullable average from an integer value you’ll need to provide a transform function to the Average funtion.

double? nullableAverage = 	
    (from m in dataContext.Moods 	 
	join g in dataContext.Groups on m.GroupGUID equals g.GUID 	 
	where g.GUID == groupGUID 	 
	select m.Level) 	
	.Average&lt;int&gt;(x =&gt; new double?(x));  
int average = (int)Math.Round(nullableAverage.HasValue ? nullableAverage.Value : 0, 0);  
// ... 

custom application settings

posted by alexis reigel on june 28, 2008

Within a c# winform application I needed to store a generic collection to my settings, which I found out was not possible out of the box. It is possible though to set the required type in the properties designer dialog, but the serialization’s output is always nothing.

On my research on the internet for a solution i stumbled upon the post Tips for C# .NET Software Developers, which described that the attribute [SettingsSerializeAs(SettingsSerializeAs.Binary)] was required for the settings property, and to set it accordingly in the Settings.Designer.cs file. The problem here is that modifying designer generated code file is not the best of all ideas, as the manual changes are overwritten every time the settings are modified by the designer. Thus, I followed the msn article on how to create application settings, which told me to create a custom settings class. The drawback with this solution is that I now have two settings classes, and not only one single to cover it all.

Here’s an example of the settings class. Note the use of the SettingsSerializeAs attribute, as it is the key to the successful serialization.

using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;

namespace Koffeinfrei
{
    /// &lt;summary&gt;
    ///   This class provides extended settings. Use this class for types that need to have special     
    ///   attributes for serialization, that cannot be set using the config designer dialog.
    /// &lt;/summary&gt;
    internal class ExtendedSettings : ApplicationSettingsBase
    {
        private static readonly ExtendedSettings defaultInstance =
            ((ExtendedSettings) (Synchronized(new ExtendedSettings())));

        /// &lt;summary&gt;
        ///   Returns the default instance of this class.
        /// &lt;/summary&gt;
        /// &lt;remarks&gt;
        ///   Get the value of the &lt;see name="defaultInstance" /&gt; member.
        /// &lt;/remarks&gt;
        public static ExtendedSettings Default
        {
            get { return defaultInstance; }
        }

        /// &lt;summary&gt;
        ///   The &lt;see cref="SomeCustomClass" /&gt;s stored in the user scoped settings.
        /// &lt;/summary&gt;
        /// &lt;remarks&gt;
        ///   Get / set the value of the &lt;c&gt;CustomClasses&lt;/c&gt; property.
        /// &lt;/remarks&gt;
        [UserScopedSetting]
        [DebuggerNonUserCode]
        [SettingsSerializeAs(SettingsSerializeAs.Binary)]
        public Queue&lt;SomeCustomClass&gt; CustomClasses
        {
            get { return ((Queue&lt;SomeCustomClasses&gt;) (this["CustomClasses"])); }
            set { this["CustomClasses"] = value; }
        }
    }
}

EDIT

Thanks to partial classes you can merge the custom settings to the main settings. Just use the same class name internal class Settings.

ruby blood through your .net veins with a vengeance

posted by alexis reigel on june 28, 2008

In my last blog entry i totally neglected the fact that there are lamda expressions. This nice little C# 3.0 feature makes anonymous methods much more readable. With that in mind, we can make our Times method much nicer.

Example 1: Ruby style iterator with lambda expression

2.Times( number => { Console.WriteLine("> " + number); } ); 

Compared to the former syntax, it increases readability considerably.

Example 2: Ruby style iterator with bare delegate

2.Times( 
    delegate(int number)   
	{     
	    Console.WriteLine("> " + number);   
	}
);

ruby blood through your .net veins

posted by alexis reigel on april 07, 2008

No other programming language has been syntactically as nice as ruby. Ruby is fully object oriented, most other languages appear to be not so consistent, especially when it comes to primitive data types vs classes. In ruby, everything is an object, in many other object oriented language this is not the case. Most of them have primitive data types besides classes, which means that you cannot necessarily call methods on all types. And, ruby’s syntax lets you write much functionality with little code.

But ruby is not alone, .NET is catching up a bit with each release. Now with version 3.5, M$ has introduced extension methods. They allow to extend classes dynamically, without the need to subclass.

My first thought was, let’s .NET look more like ruby, in respect to its fully ojbect oriented data types. In ruby you could write 2.times {...} to create a neat loop. In .NET, this is now possible too! You just have to write a static class with static methods, where its first paramater is prefixed with this. The first parameter defines the class type the method is added to. That’s it. You can even overload methods. And, the newly created methods popup in intellisense!

Extension methods - intellisense

2.Times? The rubyists among you know where this is going…

Example 1: Extend String class

Let’s extend the string class with an overloaded Replace-Method that performs a regexp replace.

public static class StringExtensions
{
    public static string Replace(this string stringRef, string pattern, string replace, RegexOptions options)
    {
        return Regex.Replace(stringRef, pattern, replace);
    }
}

Call it like this:

public class Program
{
    private static void Main(string[] args)
    {
        string stringOrig = "this is stupid.";
        string stringReplaced = stringOrig.Replace(@"(this) is ([^\.]+)\.", "$1 is not $2!", RegexOptions.None);
        Console.WriteLine(string.Format("Orginal string: {0}\nReplaced string: {1}", stringOrig, stringReplaced));
        Console.ReadLine();
    }
}

Pretty neat so far huh? But now, let’s face the 2.times code.

Example 2: Create a ruby style iterator

public static class IntegerExtensions
{
    public delegate void IntegerExtensionsDelegate(int intRef);

    public static bool IsEven(this int intRef)
    {
        return intRef % 2 == 0;
    }

    public static void Times(this int intRef, IntegerExtensionsDelegate invokeMethod)
    {
        for (int i = 0; i < intRef; ++i)
        {
            invokeMethod(i);
        }
    }
}

Let’s call it now:

public class Program
{
    private static void Main(string[] args)
    {
        /* ruby heart beats faster */
        if (2.IsEven())
        {
            Console.WriteLine("Number 2 is even!");
        }
        Console.WriteLine("And now: 2 times loop"); 
        /* ruby heart collapses in bliss */
        2.Times(delegate(int number) { Console.WriteLine("> " + number); });
        Console.ReadLine();
    }
}

The Times method almost looks like a ruby iterator with a block assigned. Instead of having a block, we just pass a anonymous method (aka. delegate) to the Times method, and we pretty much get what we wanted.

If you’re interested in details on the compiler output, you can read about it on Scott Hanselmann’s Computer Zen.