Typed Programming 22

Typed programming can be nice but when you have to write something like this things have gone too far:

Microsoft.Msn.Hotmail.SortBy _sortBy = (Microsoft.Msn.Hotmail.SortBy)
   Enum.Parse(typeof(Microsoft.Msn.Hotmail.SortBy), aSortBy);

Compared to a dynamic typed language:

var _sortBy = aSortBy;
  • http://webmagics.net Sebastian

    A really nice example you have found there. But I (a python fan) could not find what you genereally find nice in typed programming. Mainly you have to write much more to get the same result there.

  • http://erik.eae.net Erik Arvidsson

    Static typing has type checking at compile time that prevents a few errors. It is also faster because less run time checks needs to be done.

    IMHO, the best of both worlds is type inference. Since you like Python (and so do I but I don’t have any real world experience with it) I think you shoud take a quick look at Boo (a Python like language for .NET).

  • http://www.marxidad.com Mark Cidade

    You don’t *have* to write it that way. In C# 1.0, you can do this:

    using Microsoft.Msn.Hotmail;
    /* … */
    SortBy _sortBy = (SortBy) Emum.Parse(typeof(SortBy),aSortBy);

    Although, the functional equivelant of “var _sortBy = aSortBy” would be “string _sortBy = aSortBy”.

    In C# 3.0, you can also write “var _sortBy = aSortBy;” and instead of “var aFunction = function(x){return x+1;}”, you can write “var aFunction = x => x+1;” and have that checked at compile time.

  • http://erik.eae.net Erik Arvidsson

    In C# 1.0 you still have to repeat the typename three times. That’s at least 2 times too often. By the way can’t one do something like Foo.Bar.EnumType.parse(val)?

  • http://stage.bennettadelson.com/bennettadelson/blogs/rbuckton/default.aspx Ron Buckton

    In C# 3.0 the proposed “var” keyword provides pseudo-dynamic typing through compile-time type inference. If aSortBy is a System.String or System.Object the type of _sortBy would be System.String or System.Object.

    so you would still have to do (SortBy)Enum.Parse(typeof(SortBy), aSortBy); and you’re only saving yourself 3 characters compared to the normal syntax. “var” is only being introduced to help deal with “types you can’t say” because they are compiler generated. Also “var” can only be used in a local scope, not at the class level.

    e.g.

    var person = new { Name = “Bob Smith”, Phone = “(817) 555-1234″ };
    Console.WriteLine(person.Name);

    What enum really needs is a generic version, however it was skipped because you can’t supply a constraint of “where T: Enum” because “Enum” is a special type. Really the right way would be:

    SortBy _sortBy = Enum.Parse(aSortBy);

  • http://stage.bennettadelson.com/bennettadelson/blogs/rbuckton/default.aspx Ron Buckton

    The bracketing didn’t show up. It would be:

    SortBy _sortBy = Enum<SortBay>.Parse(aSortBy);

  • http://erik.eae.net Erik Arvidsson

    Still that also requires you to write the type name 3 times. That whole concept is flawed. This is what one would like to achieve:

    SortBy _sortBy = aSortBy;

    or

    var _sortBy = (SortBy) aSortBy;

    the type of aSortBy is a string but enums may have a value associated with each value and in this case the values are the same so the compliler should be able to do this for you.

    I’ve been away from typed languages for too long and I’m getting lazy.

  • http://www.marxidad.com Mark Cidade

    The comparison to “var _sortBy = aSortBy” is still invalid if you’re comparing that to JavaScript since JavaScript doesn’t even have enumerations at all.

    Another feature of C# 3.0 is that you can add extension methods to existing types at a syntax level, which is similar to extending prootypes in JavaScript. So where in JavaScript you would type “String.prototype.toEnum = function(enumType) {return Enum.Parse(enumType,this);}”, in C# you’d first have to write a static class, then import it:

    class StringExtension
    { static T ToEnum<T&gt where T : Enum (this string str) {return (T) Enum.Parse(typeof(T), str);}
    }
    —-
    using StringExtension;
    /*…*/
    var _sortBy = aSortBy.ToEnum<SortBy>();

  • http://erik.eae.net Erik Arvidsson

    We’re not even at C# 2.0 and you are already talking about C# 3.0 :-)

  • http://erik.eae.net Erik Arvidsson

    Mark: Since you seem to have a good understanding of C# you might be able to explain to me why typof is needed? To me, doing typeof(T) where T is already a Type seems useless. I know it is required but I never took the time to understand the reasoning behind it.

  • http://www.marxidad.com Mark Cidade

    My best guess as to why you can’t just use the naked type name to refer to the corresponding System.Type object is because writing a parser for that would be complicated if not impossible, because naked type names are used for member and variable declarations as well as in things like the casting operator.

    In Python, every class seems to be implemented as a callable object in the same way methods are, so if you leave out the parantheses, you’ll get the class (or method) object. Also, type names aren’t used as metadata in any kind of declaration so the appearance of a type name always refers to the class object in any context.

    In .NET, even though types are represented by instances of the System.Type class, type declarations don’t actually create new objects–System.Type objects are created on demand, like when you call GetType() on an object or use the typeof() operator.

    It may very well be possible to write a parser that allows for naked type names that refer to the System.Type object, but it may just be the language designers’ choice to make it explicit by using the typeof operator. Otherwise, it may be too confusing for some people to have naked type names meaning different things in different contexts and it increases the chances of some errors, like when you type “x = (Int32);” but forgot to type the identifier for something that you want casted as an int (as in “x = (Int32) y;”), and so the compiler treats it as “x = typeof(Int32);”

  • http://www.marxidad.com Mark Cidade

    Also, right now it’s possible to have a static method on a user-defined type called MyClass.GetType(). If “MyClass” refered to typeof(MyClass), then MyClass.GetType() would always return typeof(System.Type) and I wouldn’t be able to have a user-defined static MyClass.GetType() that I could call. Not necessarily a bad thing, but that would make forbidden any static method names that were also instance names of System.Type, which is currently subject to change (by adding members) with each version of the framework.

  • http://erik.eae.net Erik Arvidsson

    It got nothing to do with the parser. It is simple enough and not very confusing. A lot of languages supports this. The problem as I see it is that classes are not first class citizens i C# and the only reason for that that I can think of backwards compatibility with C++ which is backwards compatible with C and so on.

    Classes should be objects of type Type. Simple as that. The following works in JS2:

    const N : Type = Number;
    function abs(n : N) : N {
    return n < 0 ? -n : n;
    }

    // not very useful example but shows that Types are first class
    // citizens
    function myInstanceOf(obj : Object, t : Type) : Boolean {
    return obj instanceof t;
    }

    class A {}
    var a = new A;
    myInstanceOf(a, A)

  • http://www.marxidad.com Mark Cidade

    I think that the main reason C# doesn’t have classes as objects is because the .NET framework isn’t that way. One possible reason that the framework isn’t that way may be because then a lot of languages would have to change their semantics more than they would with the existing implementation.

    Your first example is equivelant to the following C#:

    using N = Number;
    /* … */
    N abs(N n) {return n < 0 ? -n : n;}

    Using type names to refer to type objects seems to have something to do with the parser. In the JS2 spec, it says, “The language cannot syntactically distinguish type expressions from value expressions, so a type expression can be any compile-time constant expression that evaluates to a type. A type is also a value (whose type is Type) and can be used in expressions, assigned to variables, passed to functions, etc.”

    I don’t know how JS2 would deal with static members of user-defined types that are the same as Type’s instance members. The typeof operator is needed in C# for disambiguating in that situation. In Python, a type’s static methods hide any of the “type” type’s instance methods that have the same name (which in this case, isn’t a big deal, since all but “mro” use the reserved __doubleUnderscore__ convention).

  • http://codinginparadise.org Brad Neuberg

    JavaScript 2.0, as implemented in the newer versions of Macromedia Flash, is pretty nice; the programmer gets to choose whether they want type checking or not:

    var priceItem:Number = 14.95;

    or

    var priceItem = 14.95;

    are both allowed. This can be really nice, since it can allow a programmer to use type checking to make things more clear, in method arguments for example:

    function play(location:URL) {
    }

  • http://erik.eae.net Erik Arvidsson

    I haven’t used JS2 in Flash but I’ve seen a lot of code written for it and they have a tendency to use:

    var o : Object = new Foo;

    Doesn’t it support using Foo as the type?

  • http://www.marxidad.com Mark Cidade

    Flash’s ActionScript allows custom types for what they call strict typing. But it seems that type safety only applies to strictly typed variables that are assigned to other strictly typed variables, so I wouldn’t call it strongly typed.

    var myFoo : Foo = new Foo();
    var myString : String = “bar”;
    var notTyped = “baz”;
    myFoo = myString; //error
    myFoo = notTyped; //no error

    see http://livedocs.macromedia.com/flash/mx2004/main_7_2/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Flash_MX_2004&file=00000780.html and the comments on http://livedocs.macromedia.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001890.html

  • .net noobie

    .NET rules
    and
    .NET 2.0 Kicks Butt+

    I find the Typed language and Visual Studios.NET’s Intellisence a god send :)

  • http://www.weverwijk.eu Marco

    Hmm, .NET Rules? Is this supposed to become a discussion between “Typed Programming languages”? If so, i preffer JAVA!

  • http://insuranceready.googlepages.com/ peter

    It got nothing to do with the parser. It is simple enough and not very confusing. A lot of languages supports this. The problem as I see it is that classes are not first class citizens i C# and the only reason for that that I can think of backwards compatibility with C++ which is backwards compatible with C and so on.

  • http://jrdev.org Brian

    Actually you never have to type out a namespace in .net, if you use visual studio.

    Microsoft.Msn.Hotmail.SortBy

    “M”, ctr+space, enter,”.”, “M”, enter, “.”, “H”, enter,”S”,”o”, enter. 12 keystrokes.

  • http://www.fire-proxy.com/ proxy site

    …I think that the main reason C# doesn’t have classes as objects is because the .NET framework isn’t that way. One possible reason that the framework isn’t that way may be because then a lot of languages would have to change their semantics more than they would with the existing implementation….