C# 4, part 4: My manifesto and wishlist

The final part of this little series is the one where I suggest my own ideas for C# 4, beyond those I’ve already indicated my approval for in earlier posts. Before I talk about individual features, however, I’d like to put forward a manifesto which could perhaps help the decision-making process. I hasten to add that I haven’t run all the previous parts through this manifesto to make sure that I’ve been consistent, but all of these thoughts have been running around in my head for a while so I hope I haven’t been wildly out.

Manifesto for C# 4

I would welcome the following goals:

Remember it’s C#

Many suggestions have been trying to turn C# into either Ruby, LISP, or other languages. I welcome diversity in languages, and I believe in using the right tool for the job – but that means languages should stick to their core principles, too. Now, I know that sounds like I might be bashing C# 3, given how much that has borrowed from elsewhere for lambda expressions and the like, and I don’t know exactly how I square that circle internally – but I don’t want C# to become a giant toolbox that every useful feature from every language in existence is dumped into.

There are useful ideas to think about from all kinds of areas – not just existing languages – but I’d be tempted to reject them if they just don’t fit into C# neatly without redefining the whole thing.

Consider how people will learn it

I’ve mentioned this before, but I am truly worried about people learning C# 3 from scratch. One of the reasons I didn’t attempt to write about C# from first principles, instead assuming knowledge of C# 1, is that I’m not sure people can sensibly learn it that way. Now, I don’t think I can sensibly get inside the head of someone who doesn’t know anything about C#, but I suspect that I’d want to cover query expressions right at the very end, preferably after quite a while of experience in C# without them.

That might not go for every new feature – it’s probably worth knowing about automatic properties right from the start, for instance, and introducing lambda expressions at the same time as anonymous methods (if C# 3 is the definite goal) but expression trees would be pretty late in my list of topics.

I learned C# 1 from a background of Java, and it didn’t take long to understand the basics of the syntax. Many of the subtleties took a lot longer of course (and it was a very long time before I really understood the differences between events and delegates, I’m sad to say) but it wasn’t a hard move. For a long time C# 2 just meant generics as far as I was concerned – with occasional nullable types, and some of the simpler features such as differing access for getters and setters. Anonymous methods and iterator blocks didn’t really hit me in terms of usefulness until much later – possibly due to using closures in Groovy and more iterators in LINQ. I suspect for many C# 2 developers this is still the case.

My method of learning C# 3 (from the spec, often in rather more detail than normal for the sake of accuracy in writing) is sufficiently far off the beaten track as to make it irrelevant for general purposes, but I wonder how people will learn it in reality. How will it be taught in universities (assuming there are any that teach C#)? How easily will developers moving to C# from Java cope? How about from other languages?

Interestingly, the move from VB 9 to C# 3 is now probably easier than the move from Java 6 to C# 3. Even with the differences in generics between Java and C#, that probably wasn’t true with C# 2.

To get back to C# 4, I’d like the improvements to be somehow blend in so that learning C# 4 from scratch isn’t a significantly different experience to learning C# 3 from scratch. It’s bound to be slightly longer as there will certainly be new features to learn – but if they can be learned alongside existing features, I think that’s a valuable asset. It’s also worth considering how much investment will be required to learn C# 4 from a position of understanding C# 3. Going from C# 2 to C# 3 is a significant task – but it’s one which involves a paradigm shift, and of course the payoffs are massive. I’d be very surprised (and disappointed) to see the same level of change in C# 4, or indeed the same level of payoff. Conservative though this is, I’m after “quick wins” for developers – even if in some cases such as covariance/contravariance the win is far from quick from the C# design/implementation team’s perspective.

Just to put things into perspective: think about how many new technologies developers have being asked to learn in the last few years – WCF, WPF, Workflow Foundation, Cardspace, Silverlight, AJAX, LINQ, ClickOnce and no doubt other things I’ve forgotten. I feel a bit like Joseph II complaining that Mozart had written “too many notes” – and if you asked me to start exorcising any of these technologies from history I’d be horrified at the prospect. That doesn’t actually make it any easier for us though. I doubt that the pace of change is likely to slow down any time soon in terms of technologies – let’s not make developers feel like complete foreigners in a language they were happy with.

Keep the language spec understandable

I know there aren’t many people who look at the language spec, but the C# spec has historically been very, very well written. It’s usually clear (even if it can be hard to find the right section at times) and leaves rigidly defined areas of doubt and uncertainty in appropriate places, while stamping out ambiguity in others. The new unified spec is a great improvement over the “C# 1 … and then the new bits in C# 2″ approach from before. However, it’s growing at a somewhat alarming rate. As it grows, I expect it to become harder to read as a natural consequence – unless particular effort is put into countering that potential problem.

Stay technology-neutral…

Okay, this one is aimed fairly squarely at VB9. I know various people love XML literals, but I’m not a fan. It just feels wrong to have such close ties with a particular technology in the actual language, even one so widely used as XML. (Of course, there’s already a link between XML and C# in terms of documentation comments – but that doens’t feel quite as problematic.)

My first reaction to LINQ (before I understood it) was that C# was being invaded by SQL. Now that I’ve got a much better grasp of query expressions, I have no concern in that area. Perhaps it would be possible to introduce a new hierarchy construct which LINQ to XML understands with ease – or adapt the existing object/collection initializers slightly for this purpose. With some work, it may be possible to do this without restricting it to XML… I’m really just blue-skying though (and this isn’t a feature on my wishlist.)

… but bear concurrency in mind

While I don’t like the idea of tying C# to any particular technology, I think the general theme of concurrency is going to be increasingly important. That’s far from insightful – just about every technology commentator in the world is predicting a massively parallel computing landscape in the future. Developers won’t be able to get away with blissful ignorance of concurrency, even if not everyone will need to know the nuts and bolts.

Make it easier to do the right thing

This is effectively encouraging developers to “fall into the pit of success”. Often best practices are ignored as being inconvenient or impractical at times, and I’m certainly guilty of that myself. C# has a good history of enabling developers to do the right thing more easily as time progresses: automatic properties, iterator blocks and allowing different getter/setter access spring to mind as examples.

In some ways this is the biggest goal in this manifesto. It’s certainly guided me in terms of encouraging mixin and immutability support, ways of simplifying parameter/invariant checking, and potentially IDisposable implementation. I like features which don’t require me to learn whole new ways of approaching problems, but let me do what I already knew I should do, just more easily.

Wishlist of C# 4 features

With all that out of the way, what would I like to see in C# 4? Hopefully from the above you won’t be expecting anything earth-shattering – which is a good job, as all of these are reasonably minor modifications. Perhaps we could call it C# 3.5, shipping with .NET 4.0. That would really make life interesting, as people are already referring to C# 3 as C# 3.5 (and C# 2008)…

Readonly automatic properties

I’ve mentioned this before, but I’ll give more details here. I’d like to be able to specify readonly instead of protected/internal/private for the setter access, which would:

  • Mark the autogenerated backing variable as initonly in IL
  • Prevent code outside the constructor from setting the property

So, for example:

 

class ReadOnlyDemo
{  
    public string Name { get; readonly set; }

    public ReadOnlyDemo(string name)
    {
        // Valid
        Name = name;
    }
   
    public void TryToSetName(string newName)
    {
        // Invalid
        Name = newName;
    }
}

This would make it easier to write genuinely (and verifiably, as per Joe’s post) immutable classes, or just immutable parts of classes. As mentioned in previous comments, there could be interesting challenges around serialization and immutability, but frankly they really need to be addressed anyway – immutability is going to be one part of the toolkit for concurrency, whether it has language support or not. In the generated IL the property would only have a getter – calls to the setter in the constructor would be translated into direct variable sets.

This shouldn’t require a CLR change.

Property-scoped variables

I’ve been suggesting this (occasionally) for a long time, but it’s worth reiterating. Every so often, you really want to make sure that no code messes around with a variable other than through a property. This can be solved with discipline, of course – but historically we don’t have a good record on sticking to discipline. Why not get the compiler to enforce the discipline? I would consider code like this:

 

public class Person
{
    public int Age
    {
        // Variable is not accessible outside the Age property
        int age;
        get
        {
            return age;
        }
        set
        {
            if (value < 0 || value > SomeMaxAgeConstant)
            {
                throw new ArgumentOutOfRangeException();
            }
            age = value;
        }
    }

    public void SetAgeNicely(int value)
    {
        // Perfectly legal
        Age = value;
    }

    public void SetAgeSneakily(int value)
    {
        // Compilation error!
        age = value;
    }
}

 

Just in case Eric’s reading this: yes, having Age as a property of a person is a generally bad idea. Specifying a date of birth and calculating the age is a better idea. Really, don’t use this code as a model for a Person type. However, treat it as a dumb example of a reasonable idea. I need to find myself a better type to use as my first port of call when finding an example…

The variable name would still have to be unique – it would still be the name generated in the IL, for instance. Multiple variables could be declared if required. The generated code could be exactly the same as that of existing code which happened to only use the property to access the variable.

A couple of potential options:

  • The variables could be directly accessible during the constructor, potentially. This would help with things like serialization.
  • Likewise, potentially an attribute could be applied to other members which needed access to the variables. Bear in mind that we’re only trying to save developers from themselves (and their colleagues). We’re not trying to cope with intruders in a security sense. An active “I know I’m violating my own rules” declaration should cause enough discomfort to avoid the accidental issues we’re trying to avoid.

This shouldn’t require a CLR change.

Extension properties

This has been broadly talked about, particularly in view of fluent interfaces. It feels to me that there are two very different reasons for extension properties:

  1. Making fluent interfaces prettier, e.g. 19.June(1976) + 8.Hours + 20.Minutes instead of 19.June(1976) + 8.Hours() + 20.Minutes()
  2. Genuine properties, which of course couldn’t add new state to the extended type, but could access it in a different way.

Point 1 feels like a bit of a hack, I must admit. It’s using properties not because the result is “property-like” but because we want to miss the brackets off. It’s been pointed out to me that VB already allows this, and that by brackets to be missed out for parameterless methods we could achieve the same effect – but that just feels wrong. Arguably fluent interfaces already mess around with the normal conventions of what methods do and how they’re named, so using properties like this probably isn’t too bad.

Point 2 is a more natural reason for extension properties. As an example, consider a type which exposes a Size property, but not Width or Height. Changing either dimension individually requires setting the Size to a new one with the same value for the other dimension – this is often much harder to read than judicious use of Height/Width. I suspect that extension properties would actually be used for this reason less often than for fluent interfaces, but there may be any number of interesting uses I haven’t thought of.

This shouldn’t require a CLR change, but framework changes may be required.

Extension method discovery improvements

I’ve made it clear before now that the way extension methods are discovered (i.e. with using directives which import all the extension methods of all the types within the specified namespace) leaves much to be desired. I don’t like trying to reverse bad decisions – it’s pretty hard to do it well – but I really feel strongly about this one. (Interestingly, although I’ve heard many people criticising this choice, I don’t actually remember hearing the C# team defending it. Given that reservations were raised back in 2005, when there was still plenty of time to change stuff, I suspect there are reasons no-one’s thought of. I’d love to hear them some time.)

The goal would be to change from discovering extensions at a namespace to discovering extensions at a type level. (By which I mean at a “type containing extension methods” level – e.g. System.Linq.Enumerable or System.Linq.Queryably. Admittedly discovery on a basis which explicitly specifies the type to extend would also be interesting.) I don’t mind exactly how the syntax works, but the usual ideas are ones such as:

 

static using System.Linq.Enumerable;
using static System.Linq.Enumerable;
using class System.Linq.Enumerable;

 

That’s the easy part – the harder part would be working out the best way to phase out the “old” syntax. I would suggest a warning if extension methods are found and used without being explicitly mentioned by type. In C# 4 this could be a warning which was disabled by default (but could be enabled with pragmas or command line switches), then enabled by default in C# 5 (but with the same options available, this time to disable it). By C# 6 we could perhaps remove the ability to discover extension methods by namespace altogether, so the methods just wouldn’t be found any more.

The C# team could be more aggressive than this, perhaps skipping the first step and making it an enabled warning from C# 4 – but I’m happy to leave that kind of thing to them, without paying it much more attention. I know how seriously they take breaking changes.

No CLR changes required as far as I can see.

Implicit “select” at end of query expressions

I can’t say I’ve used VB9′s LINQ support, but I’ve heard about one aspect which has some appeal. In C# 3, every query expression ends with either “select” or “groupby”. The compiler is actually smart enough to ignore a redundant select clause (except for degenerate query expressions ) and indeed the language spec makes this clear. So why require it in the query expression in the first place? As a concrete example of before/after:

 

// Before
var query = from user in db.Users
            where user.Age > 18
            orderby user.Name
            select user;

// After
var query = from user in db.Users
            where user.Age > 18
            orderby user.Name;

 

This isn’t a massive deal, but it would be quite neat. I worry slightly that there could be significant costs in terms of the specification complexity, however.

Internal members on internal interfaces

Interfaces currently only ever have public members, even if the interfaces themselves are internal. This means that implementing an internal interface in an internal class still means making the implementing method public, or using explicit interface implementation (which imposes other restrictions, particularly in terms of overriding). It would be nice to be able to make members internal when the interface itself is internal – either explicitly or implicitly. Implementing such members publicly would still be allowed, but you could choose to keep the implementation internal if desired.

This may require a CLR change – not sure.

“Namespace+assembly” access restriction

It’s not an uncommon request on the C# newsgroup for the equivalent of C++’s “friend” feature – where two classes have a special relationship. In many ways InternalsVisibleTo is an assembly-wide version of this feature, but I can certainly see how it would be nice to have a slightly finer grained version. Sometimes two classes are naturally tightly coupled, even though they have distinct responsibilities. Although loose coupling is generally accepted to be a good thing, it’s not always practical. At the same time, giving extra access to all the types within the same assembly can be a little bit much.

Instead of specifying particular types to share members with, I’d propose a new access level, which would make appropriately decorated members available to other types which are both within the same assembly and within the same namespace. This would be similar to Java’s “package level” access (the default, for some reason) except without the implicit availability to derived types. (Java’s access levels and defaults are odd to say the least.)

(Of course, this wouldn’t help in assemblies which consisted of types within a single namespace.)

This would almost certainly require a CLR change.

InternalsVisibleTo simplification for strongly named assemblies

This one’s just a little niggle. In order to use the InternalsVisibleToAttribute to refer to a strongly named assembly (which you almost always have to do if the declaring assembly is strongly named), you have to specify the public key. Not the public key token as the documentation claims, but the whole public key. Not only that, but you can’t have any whitespace in it – so you can’t use a verbatim string literal to easily put it in a block. Instead, you either have to have the whole thing on one line, or use compile-time string concatenation to make sure the key is still unbroken.

It’s not often you need to look at the assembly attributes, so it’s far from a major issue – but it’s a mild annoyance which could be fixed with very few downsides.

This may require a CLR change – not sure.

Is that all?

I suspect that soon after posting this, I’ll think of other ideas. Some may be daft, some may be more significant than these, but either way I’ll do a new post for new ideas, rather than adding to this one. I’ll update this one for typos, further explanations etc. I suspect if I don’t post this now I’ll keep tweaking it for hours – which is relatively pointless as I’m really trying to provoke discussion rather than presenting polished specification proposals.

39 thoughts on “C# 4, part 4: My manifesto and wishlist”

  1. Ah, thank goodness someone who actually gets listened to is concerned about everything getting thrown into C# haphazardly. If it turns into some sort of bastard dynamic-functional lovechild of PHP and Haskell, I’ll probably sulk my way back to Java or C++.

  2. Hi Jon, I think I like your property-based ideas, especially the property-scoped variables, but still wonder how something like WCF serialisation might work? I think it uses reflection for most of its deserialising so those property-variables will need to be accessible via reflection… which means some changes to the way reflection classes work (no longer just a property or a field). Thoughts?

  3. For the record, I’ve no idea whether or not I’m listened to inside MS. I have the good fortune to have conversations with Eric and occasionally Mads, Wes and a few others – and those conversations occasionally include language design.

    However, I have no idea whether anything I say goes any further – although I’d at least hope that if it does, there’s a filter involved to get rid of the dross.

    I’m fine with that – I still get to have the interesting conversations, after all. Also, if it all goes horribly wrong, no one can blame me :)

  4. Steven: No changes required for reflection. There would be no changes at all as far as the compiled code was concerned – it would be purely a compile-time issue, like implicitly typed local variables are in C# 3. WCF would never know the difference :)

    (But yes, you’d need to be aware that anything messing around with reflection *would* be able to set fields directly.)

  5. Steven: Just rereading your comment, which particular feature were you talking about in terms of WCF serialization? I was taking it to be property-scoped variables, but I could be wrong :)

  6. Agree whole-heartedly to most.

    Re [InternalsVisibleTo]
    I agree it is a major pain, but there are lots of other things I’d rather them work on; also:
    “Not the public key token as the documentation claims”
    I can’t find anywhere that claims you *can* use the key-token (maybe they’ve fixed the documentation). Additionally, MSDN mentions that the CLR will raise MethodAccessException (if the compiler tries to cheat), so it would (as I interpret it) require CLR changes.

  7. Yes, I think they’ve fixed the documentation. It’s been inaccurate in a number of ways in the past. In particular, in the local copy I’ve got it claims that “This attribute can only be applied to strong-named assemblies.”

    The online docs (http://msdn2.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx)
    have an example which looks like it’s trying to use a public key token – and I’m sure I’ve seen docs of some kind suggesting that that will work. (There’s also a fair amount of misinformation on the web about it – a search for “public key token” and InternalsVisibleTo yields too many hits…)

    By the looks of some of the hits, I suspect that this was available in betas of .NET 2.0, but was made stricter for the release. My guess is that some docs didn’t catch up for a while.

    I’d *thought* there was a compiler error suggesting that the public key token should be used too, but I can’t reproduce that now.

  8. Property-scoped variables.
    Would you also expect the following to work?
    public class Person {
    public int Age
    {
    int age;
    get { return age; }
    }
    private int age;
    }

    … how would you address the conflict if trying to get at Age’s age in the c’tor?

    Extension properties: common sense. If you can write an extension method “int get_Age(this SomeClass someClass)” it should support properties… I’m sure Eric or Mads may have an explanation why it wasn’t in C# 3…

    Implicit “select”.
    I’m not fond of this. I’m big on being explicit though…

    I agree that there should be some focus on concurrency soon in C#. That’s a big priority for me. Preferably in 4; but it depends on the agenda(s). This would include things like immutability.

    Do you think adding more dynamic-language abilities is technology-specific?

  9. I’m a newbie developer just putting my foot wet on the Software Development industry.

    To be honest, after couple months doing Java, I grew tired of “stacks” of technologies.

    Why can’t they all be as simple as PHP, MySQL, PEAR, Smarty.

    Why can’t they all be as simple as Ruby on Rails, MySQL?

    Why can’t they all be as simple as Django, wxWindows, Twisted, SQLAlchemy, and Python?

  10. Thank you for a very interesting series on C#. It really is my favorite language and im glad someone out there is keeping on eye on its progress (i know i’m not!)

    Out of this article the two things that would have an immediate positive impact on me are:

    1) Implicit SELECT statement in LINQ
    2) ReadOnly automatic properties

    Keep at it my friend,

    Dmitry.

  11. Peter:

    1) No, I wouldn’t expect your example to compile. I’ve really misnamed the feature – I’d expect the actual *scope* of the variable to be the class, but the *access* to be restricted to the property.

    2) Extension properties: I wouldn’t want an extension method to become an extension property just by convention, and I’d rather the “get_” bit was hidden – but I don’t know (yet) what syntax I’d actually like to see. It would be nice to see some proposals.

    3) Implicit select: don’t forget that at the moment you’re being explicit but the compiler is actually removing the code that you’ve explicitly written! I just find the redundancy slightly irritating sometimes.

    4) Dynamic-language stuff: I don’t think it has to be technology-specific, or rather if it ends up DLR-specific that’s general enough for me. If it were Ruby-specific or Python-specific that would be too much – but hopefully it’ll work out nicely. I do worry that it could lead to spec bloat for little benefit for most developers. (Or rather, no benefit for most developers but massive benefit for a few.)

  12. That’s a lot to respond to, so in short, let me just say ‘we hear you’.

    Future versions of C# will likely not have nearly so many world-changing paradigm-shifting new language features as generics, iterators and query comprehensions. Rather, we will be concentrating more on tooling (ie, making debugging better, etc) and on very targetted-on-alleviating-specific-pain-points features.

    I’d like to respond point-by-point in depth on a lot of these excellent topics, but that will have to wait.

  13. Dmitry:

    Interesting to now have one “+1″ for implicit select, and one “-1″ :)

    As for “with” – personally I’d rather avoid it. Object initializers in C# 3 cover the single case where I can see significant benefit – other times I’d rather declare a local variable and operate on that, or (if possible) work out why there are enough single operations happening on a type to merit “with” and then make that one composite operation on the type it’s being called on.

    Jon

  14. Eric: I’ll look forward to reading more detailed responses. Your blog would probably be a better venue for that, given that its readership is no doubt rather wider!

  15. Jon:
    “1) No, I wouldn’t expect your example to compile. I’ve really misnamed the feature – I’d expect the actual *scope* of the variable to be the class, but the *access* to be restricted to the property.”

    I don’t think it’s necessarily impossible; I’m just addressing problems the C# team would eventually have to. Anonymous types, for example, they are concrete types in IL but the compiler knows how to generate IL to address them. The same could be done for what you’ve proposed, e.g. “<>Age.age” could be a concrete member for the age “property local”, the compile would then know how to generate IL within the property setter/getter to access that member and no other member could directly access that member or define another member with the same name, allowing my code snippet to compile. I asked to see if you though that was something you’d expect–otherwise a specific error (“‘age’ cannot be declared at class scope because it is a property scope at property X”, for example).

    “2) Extension properties: I wouldn’t want an extension method to become an extension property just by convention, and I’d rather the “get_” bit was hidden – but I don’t know (yet) what syntax I’d actually like to see. It would be nice to see some proposals.”

    Yep, that’s what I meant. i.e. PropertyX is really implemented as get_|set_PropertyX under the covers. If it really is just a method, then extension properties just make sense…

    “3) Implicit select: don’t forget that at the moment you’re being explicit but the compiler is actually removing the code that you’ve explicitly written! I just find the redundancy slightly irritating sometimes.”

    Yeah, but at least it has your intention to work with; without it it’s making a big assumption. “var query = …” is understandable; but if you use using specific IQueryable or IOrderedQueryable instead of var, you’re intention would go a long way to helping the compiler.

    “4) Dynamic-language stuff: I don’t think it has to be technology-specific, or rather if it ends up DLR-specific that’s general enough for me. If it were Ruby-specific or Python-specific that would be too much – but hopefully it’ll work out nicely. I do worry that it could lead to spec bloat for little benefit for most developers. (Or rather, no benefit for most developers but massive benefit for a few.)”

    I’m just curious on your thoughts, the dynamic stuff seems to be a priority on the C# team (based on Charlie/Mad’s future focus I article, or maybe that’s just what they’re currently working on). But, it seems to me to be cross-selling Office at this point (i.e. there’s very little the average C# programmer would need to be dynamic, outside of COM programming).

  16. 1) Yes, it would be possible to rewrite the names – but I think I’d prefer it to be an error case anyway. It means less impact on other things such as the debugger etc, and encourages more understable (and refactorable) code, I suspect.

    2) Agreed. Of course, properties and normal methods aren’t the only things which end up as methods in IL…

    3) I think we’ll just have to agree to disagree on this one. It’s a matter of personal taste to a large extent.

    4) I really can’t get excited about the dynamic stuff myself at the moment. If we were allocating points for features, it wouldn’t get many from me. On the other hand, if I wanted to access a weakly typed COM API I can see it would be really, really handy. As I say, I worry about how much impact it could have on the spec for a limited breadth of benefit.

  17. +1 on “Property-scoped variables”. This is an important feature for *safe* lazy-evaluation. Right now I’m using an ugly prefix for the variable storing the value:

    private MyClass lazy_theProperty;

    public MyClass TheProperty
    {
    get
    {
    if (lazy_theProperty==null)
    lazy_theProperty=new MyClass();
    return lazy_theProperty;
    }
    }

    This would be nice:

    public MyClass TheProperty
    {
    MyClass theProperty
    get
    {
    if (theProperty==null)
    theProperty=new MyClass();
    return theProperty;
    }
    }

  18. Personally, I’d focus more on making C# a language the helps you write less buggy code.

    To this end, I’d introduce design by contract stuff, ala Spec#, some higher level concurrency abstractions, as starters.

  19. I can certainly see the similarity between “static local” and property scoped variables, but:

    a) They would occur at a position where no executable code could occur, so can’t be confused with local variables. They’re just normal instance variables which happen to be declared one level lower.

    b) They don’t use the misleading word “static”.

    c) They are shared between the getter and setter, rather than being restricted to a single method.

    I’m not a fan of static local variables, as I don’t like the idea of methods themselves having state. The idea of properties contributing to the state of the object is entirely natural though.

  20. Matt – generic type parameter covariance could never work (safely at compile-time) for List. In a future version of C# you may be able to get variance for interfaces and delegates, so long as they either only use the type parameter as input *or* only use the type parameter as output. List uses both though – add and retrieve – so variance just wouldn’t work.

  21. I think this is the first time I have ever read a technical blog post of anywhere near this length and completely agreed with everything in it (and most of the comments, too). I may have to swear off blog-reading for a while just so I can recover!

    Points that particularly resonate with me:

    “languages should stick to their core principles” – i.e. C# should be object-oriented and strongly typed, not just in the letter of the spec, but in spirit.

    “I’m after “quick wins” for developers” – me too. Extraordinarily simple things like “nameof” which would result in huge developer gains at very little cost have been put off for far too long.

    “It _just feels wrong_ to have such close ties with a particular technology…”. Absolutely. This is what domain specific languages are for. Protocols (and meta-protocols, which is what XML is) come and go with much greater frequency than programming languages.

    Property-scoped variables: “we don’t have a good record on sticking to discipline” – which is exactly why I am not a fan of dynamic languages; I want the compiler to help keep me in my place. This feature would be very useful from that perspective.

    Extension method discovery improvements – given the extreme (and IMHO irrational and self-destructive) aversion that the C# team (and the .NET team, and the entire Developer Division) has displayed in the past, I seriously doubt that this will ever happen, regardless of its merit.

    Implicit Select – I’m on the fence here. On the one hand, I like being explicit. On the other hand, I don’t like it when what I have written doesn’t match what gets compiled, which defeats the whole point of being explicit. On the other hand…I like being explicit…

    Sorry that was so long; I felt like such a well-written post deserved a fully-articulated response.

    @Eric,

    Looking forward to reading your blog posts about these features. Many of these have been kicking around in the community since C# 1.0; it would be great to hear what the C# team’s thinking is.

  22. In the Implicit “select” bit, it looks like the blog software censored you for some odd reason: the posted article says “(except for degenerate query BLOCKED EXPRESSION”. I’m guessing that “BLOCKED EXPRESSION” was supposed to be a word and a close parenthesis. I’m curious what type of degenerate query somethings will prevent the compiler from removing the redundant code.

  23. Cheetah – thanks very much for pointing it out. I’ve now added a space between “expressions” and “)” and it seems to be okay.

    To explain the post further, if you write:

    from x in numbers
    where x > 10
    select x.ToString()

    that will be compiled into
    numbers.Where (x => x > 10).Select(x => x.ToString())

    If you just select “x” though:

    from x in numbers
    where x > 10
    select x

    the compiler notices that the select isn’t really doing anything, and just emits:

    numbers.Where (x => x > 10)

    So what should a query of:
    from x in numbers
    select x

    do? The compiler is forced to output the “no-op” select, to make sure the original source doesn’t “escape”. Basically it means that every query expression will involve at least one method call.

  24. Hi!

    Great suggestions Jon – especially on allowing internal interfaces define internal members. Also, your suggestions on enhancing the property definitions with a true private variable makes sense.

    Personally, I’m really hoping that we’ll see more freedom in terms of overriding an inherited member and define the return type as one being richer than the inherited type.

    I’ve seen this feature suggested numerous times on the net (by me and others, obviously), and I really believe this feature would lead to much cleaner APIs. As far as I can see there’s really no reason why this shouldn’t be allowed.

    // common hierarchical item
    abstract class DirectoryItem
    {
    public abstract DirectoryItem Parent { get; }
    }

    // concrete hierarchical folder item
    class Folder : DirectoryItem
    {
    // perfectly valid – Folder is a DirectoryItem and should be allowed
    public override Folder Parent { get {;} }
    }

    ..

    With C# 3.0, developers have to options:

    1) Declare the “Parent” property as “new” (thus hiding the inherited “Parent” property – and, that doesn’t guarantee that the implementation on the base class gets called by means of casting)

    2) Cast the “Parent” property to the richer type when required. This is tedious, bloated and really something the developers should not mess with.

    Please comment on the above suggestion (and feel free to include the request in your own list).

    Thanks in advance and congratulations with the new job. Google sounds like a nice place to work.

  25. Yes, covariant return types would certainly be very nice. I don’t know if there are issues with it (aside from requiring a CLR change, which I believe is the case) from a type perspective.

    Jon

  26. Jon, I’ve got no idea why the left covariant return types of the framework, but it’s definately something lots of developers are asking for.

    I’d die for it – almost! :-)

  27. I know there are few of us traditional engineers transferring from Fortran to C# so nobody talks about our problems.
    I maybe asking a stupid question but why isn’t complex number built-in type?
    Second stupid question, if we have list, linked list, dictionary etc. why isn’t there a matrix collection?
    I tried to find answers to those questions, but Internet is just too vast, and getting vastier and vastier by the minute.

  28. Domagoj: Complex is an interesting question. What would it be over – just double? Is decimal or float useful here?

    As for a matrix collection – I guess scientific uses of .NET are *relatively* few. There are, of course, various 3rd party maths libraries around.

    Not great answers, I’m afraid…
    Jon

  29. In c++ there was complex I don’t see why not put the same in c# as well?
    As for scientific use, I do use 3rd party math library, but I want to switch to another and found myself at an impass cause there are no standard interfaces. And I would love to write code like
    var m = new Matrix< Complex >(n,n);
    dataGridView1.DataSource = m;
    C# is ideal for getting proof of concept done quickly, and having user interface to boot. Processing power isn’t an issue anymore (usually) but readability of code is, and that is where C# excels.

  30. Domagoj: Complex makes a lot more sense in C++ than in C# due to the way that templates differ from generics. It’s possible in C#, but losing a certain amount of compile-time safety. (Marc Gravell’s implementation wouldn’t stop Complex at compile-time, for instance.)

    These are undoubtedly useful things to have, but probably lower on Microsoft’s list of priorities than other features. The MS focus at least *seems* to be more on the business community than the scientific community, and I can’t say I blame them much for that, for various reasons.

    Jon

  31. I’m a bit fed up with writing 100 times a day the following piece of code:

    public void MyMethod(MyClass myArgument)
    {
    if (myArgument == null)
    {
    throw new ArgumentNullException(“myArgument”);
    }
    }

    I think it would be nice to have a mechanism for that kind of checking in C#4. Something like an dedicated attribute, for instance :

    public void MyMethod([CannotBeNull]MyClass myArgument)
    {
    }

  32. If automatic properties included initialization semantics, this would result in less clutter. For example:

    public int Count{get;set=10;}

    public int Count{get;private set=10;}

    public ObjX MyState{get; private set=new ObjX();}

  33. Please, please, please can we have the following:

    a) More comprehensive constraints in generics.
    b) Ability to declare generic pointers.

    Generic pointers come up a lot in systems code that is accessing user-defined managed structs that have been marshalled into unmanaged memory. But we cannot declare them.

    The reason is a) above; without some way to constrain T to be a ‘pure’ ValueType the compiler has to shout when it sees T * ptr.

    If we could have a constraint that forced T to always be a struct that could contain ONLY valuetypes or nested value type strucs, it would be dead easy to support T *.

    This has been a major hassle for some systems projects, don’t forget there is a machine underneath and an operating system and sometimes we just need to have high performance, so go on, this surely isnt a lot of work?

  34. I have a proposal for extension Properties syntax. It introduces a new ‘extension’ keyword and contextualize the ‘this’ keyword. Here it is (with ‘int’ for example):

    public extension int
    {
    public int GetTriple()
    {
    return this * 3;
    }

    public int Triple
    {
    get { return this * 3; }
    }
    }

    I found it pretty simple and readable. It would also allows static extension methods/properties. For example:

    public extension int
    {
    public static int Zero
    {
    return 0;
    }
    }

    So you could do ‘int.Zero’. What do you think about it ?

Comments are closed.