views:

8130

answers:

116

Possible Duplicate:
C# Language Speculation 4.5 / 5.0

.NET 4 and Visual Studio 2010 are finally here, along with a host of new features. But we wouldn't be who we are if we didn't long for a feature that didn't make the cut, or that was never even considered. So sound off and let the folks at Microsoft know:

What features do you want to see in .NET 5? What features do you want to see in C# 5? F#? VB.NET?

PLEASE write one proposal per answer. If you have multiple ideas, post multiple answers. It makes voting and commenting easier.

+114  A: 

I'll start with a C# 5 language request.

Tuple Packing and Unpacking

Tuples are great, but without a way to unpack them through the language itself, they're still cumbersome. I would like to see something similar to Python's tuple unpacking as part of the C# language itself. For example:

public Tuple<string, int, double> ReturnMyTuple()
{
    return "Hello World!", 42, 4.2;
}

// elsewhere: item1 is a string, item2 is an int, item3 is a double. 
var item1, item2, item3 = ReturnMyTuple();

Since "public string, int" would be a syntax error anyway, why not add some syntax sugar and make the "Tuple<>" optional?
- luiscubal

Do you mean something like this?

public string, int, double ReturnMyTuple()
{
    return "Hello World!", 42, 4.2;
}

If so, I like it. Awesome idea.

As for explicit tuple grouping syntax, I'd favor () over [] or {}, but I'd be happy with either. By explicit tuple grouping, I mean the following:

var myTuple = (42, "foo", 4.2);

is equivalent to

Tuple<int, string, double> myTuple = Tuple.Create(42, "foo", 4.2);

Meaning that syntaxes like

public (int, string, double) ReturnMyTuple()
{
    return (42, "foo", 4.2);
}

work as well.

Randolpho
Wouldn't the `out` parameter be sufficient for this? Or rather, would adding this be worth the cost considering that something that already exists gets you close?
Anthony Pegram
@Anthony - Something like this would be really useful for internal work so you don't need to define so many little data transfer classes. I've found this feature to be extremely useful in F#. I really think it deserves explicit parenthesis though.
ChaosPandion
@Anthony Pegram: yes, out parameters are a work-around. The problem with out parameters is that you have to declare the individual data types before calling the out-parameter laden method. With this syntactic sugar, you do it in one line of code.
Randolpho
`out` parameters don't allow variance, can't be returned from dynamic methods, and probably have many other drawbacks.
Gabe
This clashes horribly with existing idioms. 1) `int item1, item2, item3 = foo;` declares three ints and initializes the third. 2) If `"Hello World!", 42, 4.2` is an expression for a tuple, then `Foo("Hello World!", 42, 4.2)` is a method being called with a tuple as its only argument (as opposed to a method being called with three arguments.)
Joren
Joren: it just needs brackets (parens or braces) around the tuple.
Gabe
@Joren: then wrap the tuple unpacking in some other symbol set such as parens, brackets, or braces to differentiate. E.g. `return {"Hello World", 42, 4.2};` and `var {item1, item2, item3} = ReturnMyTuple();`
Randolpho
Since "public string, int" would be a syntax error anyway, why not add some syntax sugar and make the "Tuple<>" optional?
luiscubal
I think it would be good feature.Yet another example of using: {x,y}={y,x};
Alex
The more I use F# and Python, the more I want this feature. With .Net 4, it could even just be syntactic sugar for the Tuple type family.
codekaizen
@luiscubal: I replied to your comment by editing my answer. Is that what you meant?
Randolpho
@Randolpho: Yes, that's what I meant.
luiscubal
Miguel already implemented a PoC of language integrated tuples into gmcs: http://tirania.org/blog/archive/2009/Dec-23.html
Dykam
A serializable Tuple. Currently they have no empty constructor.
Pierre-Alain Vigeant
@Dykam: Miguel is always three steps ahead of me!
Randolpho
that is very clever!
Mike
'Since "public string, int" would be a syntax error anyway, why not add some syntax sugar and make the "Tuple<>" optional?' - @luiscubal. What about tuples that are empty, have only a single element, or are *nested within other tuples*? If another data structure which is well-suited for this syntax is introduced, you'll end up with even more inconsistencies.
Wallacoloo
You can do like Python and use () por the empty tuple and (a,) for the single-element tuple. An empty tuple inside a single-element tuple would be ((),), a function call to such would become myFunc(((),)); Awkward, but that's why you don't do such things. ;)
Kyte
Zero element tuples are quite useless to my opinion. The only possible state would be... empty.
Dykam
What wrong with `return new Tuple("Hello World!", 42, 4.2);` slightly more ascii
Chris S
The move into multiple returns could also lead to the rise of the `return result, errorcode;` approach Go took to avoid exceptions, which I admittedly fell in love with.
Jurily
@Jurily: there are pros and cons to the old C-style error code paradigm. Of course, both the pro and the con are the fact that there are no exceptions. :)
Randolpho
@wallacoloo That would be "public int, Tuple<int, int>, char foo()". Still simpler. Or maybe "public int, (int, int), char foo()"...
luiscubal
I'd like to see this, but for it to be really complete it would need to support F#-style out-parameters-to-tuple-returns transformation, e.g. if calling `bool int.TryParse(string s, out int result)` then you could write it as `success, result = int.TryParse("123")`.
Greg Beech
@Greg Beech: that'd be amazingly awesome.
Randolpho
Maybe like Matlab - with []?
rursw1
+5  A: 
  1. Creating an attribute that can only be applied to any class that derives from a given class.

  2. I should be able force attribute application, If the class derives from a particular class. So if the class X dervies from class Y, then class X must host a given attribute. And I want all these to be done via an attribute only, not by writing code-around in base class or helper class. It must be inherently supported by the Attribute.

  3. Extension properties.

  4. Better Lifecycle management of Linq2Sql DataContext or EF ObjectContext. Specifically Linq2Sql datacontext lifecycle is pathetic.

  5. Native .Net framework drivers for MySql, Oracle and DB2.

this. __curious_geek
In .NET 3.5 and earlier (not sure how far back) there was a System.Data.OracleClient namespace added. I was QUITE surprised and dismayed to see in .NET 4 that uses of the classes in this namespace now squiggle-line with a hint that they are deprecated and will be removed eventually. :(
eidylon
There are native .NET framework drivers for MySql, Oracle, and DB2. They're just not made by Microsoft.
Joel Mueller
+21  A: 

Typed Enums - Allow any enum to have its own type such as string, float, (object?).

Enum Options : String
{
    Option1 = "xxx"
    Option2 = "yyy"
}
Glennular
You cannot expect a value type definition to inherit from a reference type.
this. __curious_geek
@this.__curious_geek: object is a reference type and all structs inherit from it.
Mark Byers
Since the string values will be defined at compile time maybe the backing value of the enum can be a reference to the interned string.
ChaosPandion
I think the intention of Enumerations is to order things given a specific number. Enums having values like strings or object, would loose the concept.
Erup
Why would you need this at all? `enums` are about building one or a combination of named items; the underlying values are supposed to be meaningless and you should only have to deal with the underlying value when creating a `Flag` `enum`. If you must map a value (presumably received from a database somewhere) to an `enum`, create an explicit translation that is external to the underlying `enum` value; preferrably a [TypeConverter](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx)
Randolpho
@Glennular: Use a struct, man.
code4life
@Erup Not really. Something like SetColor(AvailableColors.Red) doesn't require ordering or specific numbers. And being able to use string values helps if you need to output to another language (HTML, SQL, etc.).
AaronSieb
@AaronSieb: `AvailableColors.Red` should be a static readonly instance of `Color` (or some similar class, assuming you're redefining GUI constructs already in place), not an enumerate.
Randolpho
@Randolpho Really? Hadn't run across that guideline before. What about other multi-state values, like PayType (Salaried, Hourly), OrderStatus (Pending, Billed, Cancelled), etc.?
AaronSieb
I think enums as true objects (like Java has) would be infinitely more helpful (you could then, for instance, have a string instance variable that you would pass to a constructor to do basically this)
BlueRaja - Danny Pflughoeft
@AaronSieb; I agree... there are places where I use enums to make sure the user is selecting a valid option, and then send out email alerts based on the action, which need a translated action name in the email message. Right now this requires Setting up an Enum for the action options, and then an array of the translated names matching the enum values in index order, and then looking up into the array each time. Being able to do a String Enum would eliminate this need. I can't even count the number of times I've longed to do a limited list of enumerate String values that are allowable.
eidylon
Just create a static class with `static readonly` values/properties. That's basically what an `Enum` is anyway.
Matthew Whited
+22  A: 

Lifting the member access ('.') operator to null to make C# code more concise.

For example, this is allowed, and gives null:

int? x, y;
x = null;
y = 1;

// answer is null here, since '+' is lifted to null
int? answer = x + y;

This, however throws a null ref exception:

class MyRefType { public string Value; }

MyRefType a, b;
a = null;
b = new MyRefType { Value = "World" };

// NullReferenceException here, since the Member Access operation is not
// lifted
var result = a.Value + b.Value; 

If it were lifted, we could expect the same behavior as the first example, instead of having to write this:

var result = (a == null ? null : a.Value) + (b == null ? null : b.Value);

IanG explains it in more detail, here:

http://www.interact-sw.co.uk/iangblog/2008/04/13/member-lifting

codekaizen
What *does* (null + null) equal?
@roygbic 2(null). duh. ;)
Ed Woodcock
Interesting... could be a valuable feature. Unfortunately, it could also cause confusion by allowing semantics that are unexpected, at least in terms of previous versions of the framework. That said, other languages (particularly SQL) have null propagation, so why not C#?
Randolpho
@Randolpho - Some may take offense to comparing C# with SQL. :)
ChaosPandion
@ChaosPandion: Heh... have you looked at LINQ lately?
Randolpho
Null propagation makes sense if the value is "unknown". But in C#, null means "nothing", not "unknown". I think it's better to leave nulls the way they are...
code4life
@code4life: I can see how this makes sense when talking about references, but in this case I'm talking about values, and 'nothing' and 'unknown' have the same meaning. IanG makes a point of showing that the lack of clear distinction could cause confusion, and raises the possibility of a specific operator for lifted member access.
codekaizen
There was a suggestion to use the following syntax: `foo.?bar.?foobar`.
Dykam
@Dykam - I can see using that... it meshes nicely with the Nullable<T> C# syntax. Perhaps, though, it would be more in line with left-to-right reading of C# statements with the '?' on the left: `foo?.bar?.foobar`...
codekaizen
Problem with that syntax is that when the parser hits that, it has to look forward to see if it's short-if or `maybe`-access.
Dykam
@Dykam - I'm sure Eric Lippert can handle that!
codekaizen
First of all, I highly suspect any changes that would actually be considered will have to be in the additive category, add to existing syntax, changing existing behavior is probably not going to get high on priorities. Microsoft has always been good on keeping existing bugs and features, so changing how "x.Value" behaves if x is null is probably going right in the no-way category (not that I consider this a bug.)
Lasse V. Karlsen
@codekaizen, it's not about if it's possible, but it affects performance and simplicity.
Dykam
A: 

Multiple Inheritance

I am being serious about that. Yes, I know it makes the language more complex. Yes, I know there are a lot of intricate details in the way the compiler resolves method calls (the diamond problem). Yes, I know there are often (and usually are) better alternatives using intefaces. But, the fact of the matter is that there really are scenarios where multiple inheritance is perfectly suited. Of course it can (or almost certainly would be) abused. But, I can say the same thing of many existing C# features. In fact, I could probably figure out a way to abuse just about all of them. I love LINQ, but I have to be honest, I have been seeing some flagrant abuses of it lately and I am sure LINQ was quite difficult to integrate in the language.

The patterns I have been seeing developers use to work around not having MI often wind up being more complex, convoluted, and harder to maintain.

I too used to be in the camp that MI causes too many problems and is not worth the effort. I have since developed a more open minded view about it recently. Think of the possibilities in implementing the MVVM pattern. You could have a view-model class that is derived from the associated domain class and a common view-model base class. That could be incredibly powerful in implementing some the new patterns associated with WPF. The only viable option we have right now is use to inheritance of multiple interfaces and duplicate the implemenation for the members on view and the view-model separately.

Brian Gideon
I am still on the fence about this. Composition almost always trumps inheritance in simplicity and maintainability.
ChaosPandion
I think this could be better addressed with real mixins rather than true MI, but +1 nonetheless.
Randolpho
I think you might be waiting a looooong time for this one :)
fearofawhackplanet
@fearofawhackplanet: You are probably right. But, who knows, maybe the second MI revolution is just around the corner. And if nothing else it is sure to be one of the more controversial requests :)
Brian Gideon
I'm not too sure about this one... I've seen some places where it'd be useful, but overall I think the complexity issue is big. Plus it'd break a lot of existing reflective code.
Aren
I've never seen a case where MI was really needed that couldn't be solved in essentially the same way with an Interface and some extension methods.
BlueRaja - Danny Pflughoeft
I really think that the complexity argument is a red herring. Inevitably when you use languages that lack try MI, you either end up with lots of code copying or complex delegating schemes to get around it. It definitely does add complexity to compiler implementations and I rather doubt that you will ever see this added to the CLR. If MS was inclined to support MI, you would have thought they would have done it from the beginning in order to make it easier to support all of their legacy C++ code.
Christopher Barber
I'm actually working on a concept of multi inheritance done right, and basing it off C#. But haven't written it down somewhere, except on some pasty. Quick mockup of it, figure it out yourself: http://pastebin.com/m0mmJ3hh Basically, seperating interface from implementation and naming extendings/implementations to prevent conflicts.
Dykam
@Christopher: Absolutey. I have found implementing the MVVM pattern quite awkward without MI, almost overly complex at times. MI could definitely clean it up.
Brian Gideon
Eiffel's implementation of MI is rather elegant - a good model for C# MI IMHO.
Kramii
-1 so I don't have to maintain crappy code in an overly complex object hierarchy. I think they did us a favor not including this, there are just way too many newbs writting C#
csharptest.net
@csharptest: I do not disagree with that. However, I can make the same argument about almost any feature in C#. Also, have you tried implementing the MVVM pattern required for WPF. You are forced to choose of only one of two options: 1) Subclass your domain object and duplicate the view-model code or 2) Subclass your view-model base class and duplicate your domain code. MI is perfect for the MVVM pattern because your view-model classes really should be able to masquerade as both.
Brian Gideon
I don't have any exp with MVVM, however there is one observation I'd point out in my ignorance. A view-model should niether be a view nor a model. The flaw isn't in the laguage as much as it is in the object model that rquires one object to be two distinct things. Just my 2 cents toward any 'need' for MI.
csharptest.net
Well, that's just it. It is both the view and the model. Or, more specifically, it is the bridge between the view and the model taking on characteristics of both. It holds both the view state and the model state. The view is not tied to the model, but more importantly it does not hold its own state. And that is why WPF implemented with MVVM is so powerful.
Brian Gideon
In my personal experience, when I felt like I needed multiple inheritance, what I really needed were mixins, ala Ruby. Just statically typed :)
Matt
+104  A: 

An in keyword.

if (x in (1, 2, 3))
{ }
  • Like Python.
  • Without having to use extension methods.
Glennular
As long as the compiler doesn't transform it into `(new int[] { 1, 2, 3 }).Contains(x)` I would be OK with this.
ChaosPandion
Since the code turns more simple, it's ok. All the changes that simplifies coding is ok (thinking about "var obj = new ImplementationHere"?)
Erup
@ChaosPandion, Wouldn't it have to, though?
code4life
@code4life - Not necessarily, ideally we want compiler features to be extremely efficient and not have to create a new array.
ChaosPandion
@ChaosPandion: I agree; in the case of a static list, the compiler would be better off building a sequence of if/else branches. But in the case of an `IEnumerable` that is on the RHS of the in keyword, it should map directly to contains.
Randolpho
I'd also like the (a..n) syntax, as in `if (x in [5..10])` or `if (x in [1, 2, 4..8, 10])`
Charles
if (new HashSet<int> { 1, 2, 3 }.Contains(x))
TrueWill
So basically a shortcut for `if (x==1 || x==2 || x==3) ...`
Hightechrider
@Hightechrider: Its not just a shortcut, its more elegant.
Erup
public static bool In<T>(this T t, T elem,params T[] array) { if (t.Equals(elem)) return true; else if (array == null) return false; else return array.Contains(t); }So you want to save the dot? Man...
macias
Perl6-like 1 <= x <= 10 will also do nicely.
Andrey Shchekin
`if (x in [1..1000000])` would sure be a lot of OR comparisons using Hightechrider's idea, or use a lot of memory with ChaosPandion's version! Andrey Shchekin's looks better!
AshleysBrain
@AshleysBrain I think to accomplish in [1...10000]. it could do an integer compare of 1 <= x <= 1000. Only two compares. The would just allow for a shorthand syntax
Glennular
@TrueWill, creating a HashSet is pointless unless you're going to do more than one comparison with it -- the setup cost is O(N) which outweighs the benefits of the O(1) lookup. Not only do you give up being able to short-circuit the check (say when x==1) but the memory overhead is unnecessary.
Drew Noakes
@Drew - sure, but (a) it's the most exact analogy in the current framework and (b) this is a trivial example. Normally you'd cache the set somewhere (readonly field, etc.). Plus I doubt that this would be a performance bottleneck in 95% of applications (usually I/O, DB, etc.).
TrueWill
@TrueWill, without wishing to seem pedantic, the most performant example (and what the compiler would do under the hood for a feature like this if you could only specify values and not collections of values) would be `if (x==1 || x==2 || x==3) ...` which doesn't require any heap allocations and runs about as fast as you could wish for. I know it's only a small difference in performance, but that assumes its not inside a tight loop somewhere.
Drew Noakes
@Drew - my point is that the hard part of this construct is the (1, 2, 3). What does that represent? In Python it would be a tuple, I think. "in" tests for collection membership, according to docs.python.org. So the question is did the OP intend this to be a new data structure with corresponding operator or just syntactic sugar?
TrueWill
+7  A: 

Arrays indexed by enums, Delphi style:

enum Weekdays { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
private int[Weekdays] dayFun = new [] { 0, 0, 1, 1, 3, 10, 8 };

// Later..
mondayFun = dayFun[Weekdays.Monday];
Blorgbeard
Isn't it the "dumb" dictionary?
TcKs
You could do: `int[] dayFun = new [] { 0, 0, 1, 1, 3, 10, 8 };` and then `int mondayFun = dayFun[(int)Weekdays.Monday];`.
Charles
BTW I have to disagree with your values. Thursday is a bit more fun because Friday is so close, and Friday is much more fun because the weekend starts at 5pm! So perhaps `{ 0, 0, 1, 3, 5, 10, 8 }`. :)
Charles
@TcKs yes, but it doesn't need to be a dictionary since enums are ints underneath. This would be more succinct, and faster.
Blorgbeard
@Charles, sure, but using the enum directly means its much harder to get a range-check error. I do agree with your revised values though.
Blorgbeard
Most definitely. I can't imagine why they didn't do this. C# is so careful about types in most cases but forces casts all over the place when you want to use enums with arrays.
Loren Pechtel
@TcKs:nope, in my country this is the absolute truth.
Behrooz
+83  A: 

Enum as a Generics constraint

I'd like to apply generic type restriction on Enum types. For example, if I have a method like this one

public void DoSomething<T>(T enum) where T: System.Enum { ... }

I got a compiler error on current version of C#.

Carlos Loth
If you need it now, try this http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx
s_hewitt
Amen! I have code right now which will check the type of the <T> being passed in and verify it is Enum if needed, but it would be REALLY nice to have this!
eidylon
+1, and I'd like the same for delegates : `class Expression<TDelegate> where T : Delegate` (currently the compiler accepts anything for TDelegate, but it will fail at runtime if it's not a delegate)
Thomas Levesque
I resorted to writing the code that needed this constraint in F# (which supports it) and calling it from C#. It's enforced by the C# compiler, interestingly.
Joel Mueller
Basic types in general. For example, `where T: [numbers only]`; The operator constraint would be another thing. (`where T: operator+`)
Markus
+29  A: 

I would love to see discriminated unions in C#. They make message passing so much easier.

public union Message
{
    Get<int, Channel>,
    Put<int, MyClass>,
    Delete<int>
}

Of course then we need pattern matching.

match (message)
{
    Get(id, channel):
    {
        // ...
    }
    Put(id, value):
    {
        // ...
    }
    Delete(id):
    {
        // ...
    }
}
ChaosPandion
+1 for pattern matching :D
Ron Warholic
I didn't understand the purpose of this construct. Could you be more descriptive please?
Victor Rodrigues
@Victor Rodrigues: check out [this wikipedia entry](http://en.wikipedia.org/wiki/Tagged_union). Basically, a discriminated union is a type that can hold be one of a small set of types. In the example of `Message` that @ChaosPandion provided, the `Message` type can be a `Get<int, Channel>` type, a `Put<int, MyClass>` type, or a `Delete<int>` type. He is using the example to show how discriminated unions can help in message passing, but it's also an excellent example of command processing.
Randolpho
You could also see it as a enum containing extra data. You can switch on them and via the switch receive data. (That's how haXe does it.)
Dykam
@Ron, @Randolpho, @Dykam : Based off the up-votes for @Victor's comment and the down-votes for my answer we may have to spread the word about pattern matching.
ChaosPandion
I can see the use of this structural languages but I'm not sure what pattern matching buys you when you have virtual functions/methods. Basically, Message is an abstract class with Get, Put, and Delete as descendent classes.
Rodrick Chapman
@noblethrasher - When dealing with actors you want to keep the implementation separate from the message. This way you can send the same message to different actors and receive different results.
ChaosPandion
What might be more well-received than to expand an already general-purpose language with more functional constructs is to have better multi-module assembly support in Visual Studio and allow a project or even a file to contain both C# and F# source, with each compiler contributing a module to the resulting assembly.
codekaizen
+92  A: 

Extension properties.

Of course the same behavior can be accomplish with extension methods. However, for consistency with the C# properties it would be great if we could create extension properties too. I don't like to write code like this

var value = someObject.Value();

and

someObject.Value(newValue);

It seems I'm programming with Java.

Carlos Loth
+1bazillions. I wanted this when Extension Methods were created. *BUT*... Attached Properties and Dependency Properties in WPF are an excellent, but kludgey, substitute.
Randolpho
http://blogs.msdn.com/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx
BlueRaja - Danny Pflughoeft
@BlueRaja: great article.
Randolpho
This would be EXCELLENT! I've heard complaints "Well, where would you store it?" In reality, storage would be up to the coder of the property, just like the implementation code for extension methods. An excellent use for this would be for keyed collections such as the HttpSessionState object in ASP.NET. Instead of writing Session("CurrentCompany") you could make a property to wrap it to Session.CurrentCompany. It just looks SO much cleaner! Check this blog... http://blogs.msdn.com/lucian/archive/2010/02/11/power11-extension-properties.aspx
eidylon
I hope never, unless you find a syntax that doesn't look like an indexer!
Ion Todirel
An extension property could easily be implemented either as the indexer, or basically just as a pair of methods with attributes, ie. `[ExtensionProperty]get_Value(this SomeObject obj)` and `[ExtensionProperty]set_Value(this SomeObject obj, int value)`, of course, I want a good clean syntax for it though.
Lasse V. Karlsen
ALL YOUR EXTENSION PROPERTY ARE BELONG TO C# 5.0
Pierreten
I have a strong suspicion that extension properties (if added) will result in reduced cohesion across the land.
Jeff Sternal
This would have to be accompanied by runtime support. Not every extension property writer inventing a unique storage mechanism would consider thread safety and weak references... a scary thought. I like it better for calculated properties, but even then, you couldn't even use them in reflection-based data binding mechanisms. Overall, thumbs down.
Ben M
+55  A: 

Arithmetic type constraints:

public T Foo<T>(T blah) where T : number {
  return blah * blah;
}
Ron Warholic
We may have to settle for operator constraints. The idea of `Number` would be a drastic change to the framework.
ChaosPandion
Operator constraints would be excellent as well. It does seem within the realm of reason however to have a contextual keyword for type constraints that simply means (byte, int, double...etc) and applies the appropriate constraints.
Ron Warholic
That would be amazingly useful.
Randolpho
Not sure. number could be seen as some kind of macro. It could expand this function automatically to Foo<int>, Foo<float>, Foo<double> and Foo<decimal>. Of course, I'm only counting number for generics, not for variable types.
luiscubal
Yeah, I was very frustrated when I discovered this could be done with C++ templates but not with C# generics.
dewald
<3 templates :P
DeadMG
My suggestion for operator constraints:`int Sum<T>(IEnumerable<T> seq) where T : operator(T=T+T){ .. }`
JulianR
I wouldnt think Numeric base type would be that great a change... basically it would be a new type which defined the basic operations (+,-,*,/,\) from which Short, Integer, Long, Double, etc. all inherited from.
eidylon
Because optional parameters isn't bad enough? public decimal Foo(decimal blah) { ... }
Ion Todirel
Better to have the constraints for operators, I agree.
Lasse V. Karlsen
Yes, but if `T` is `byte` or `short`, then `blah * blah` would be of type `int`, so the above won't work. `Foo()` couldn't return `int` either, because it wouldn't work if `T` is `double` or `float`.
Danko Durbić
@Danko: How about a `constrained(T)` keyword similar to `default(T)` to marshal the return type to whatever the passed type was. I'm not a language designer so I can't comment much on the best way to do this; but it isn't an insurmountable obstacle. Implementation aside; there is a real need for more constraints for generics so we can leverage the same code more often.
Ron Warholic
Thats going to be one nasty hack. The CTS (CLR type system) is currently not powerful enough to encode these constraints (would require something similar to type classes) But the F#-team somehow pulled it off
SealedSun
A: 

I know it will never happen but to make string a true primitive type instead of a reference type that behaves like a primitive type due to immutability.

This would then stop the madness of having to use string.IsNullOrEmpty all the time and will allow string to be correctly used with the Nullable type.

Chris Marisic
A value type can be efficiently allocated in the stack because it has a fixed size independent of its content, that's not the case with strings, although an option would be to declare value-typed strings with its size, a la old pascal-style: string[5] zipCode;
Rafa Castaneda
@Rafa all strings are already fixed in size, strings are immutable so you could never mutate a string into a different size than it's original allocation.
Chris Marisic
@Chris, strings are fixed size AFTER initialization, but the variable place is flexible sized. `string foo;` can take all lengths of a string. An Int32 is fixed size, always 32 bits.
Dykam
I know this is merely a hack, but what I do to emulate the Nullable(Of String) concept is utilize a NullOf(target As String, nullValue As String) extension method on the String class, which basically wraps the check on IsNullOrEmpty and alternating logic so that I can just call myStringVar.NullOf("default value") and it will return myStringVar if it has a value or "default value" if not.
eidylon
@Dykam I'd make the argument that the fact you bring up is trival, it doesn't matter that the variable is flexible because it'd just be a pointer anyway. Once it's assigned the size is fixed and always known. It would be like creating an array of size 0 and then later resizing it to exactly what you need.
Chris Marisic
Now I'm confused. stack allocated types are fixed length. This means you cannot assign something of a different length. You can't assign a string of 5 chars to a variable where memory for 4 chars is allocated.
Dykam
I just use an extension method on string called HasValue(). We actually have quite a few helpful extension methods for string that are very handy. I like it that way. I can implement only what I need.
John
+45  A: 

Here's another thought spawned by @Glennular's answer:

Automatic Flag Enums

Rather than force us to define the values of flags, allow enums defined with a [Flags] attribute to automatically enumerate in powers of two. The compiler would need to be smart enough to recognize combination definitions such as ValueCombining1And2 = Value1 | Value2, but could otherwise just enumerate in powers of two.

Example:

[Flags]
public enum MyFlags
{
    Value1,   // 1
    Value2,   // 2
    ValueCombining1And2 = Value1 | Value2, // 3
    Value3,   // 4
    Value4,   // 8
    ValueCombining3And4 = Value3 | Value4 // 12    
}

If adopted, it should only work if the [Flags] attributed enum has no custom values defined (other than as laid out above).

Others (see comments) have suggested an overloaded constructor for Flags to indicate enumerating at 0 or 1 along powers of two. I say, great idea!

Randolpho
devio
@devio: Yes. Yes it would. Edited.
Randolpho
This could be done [without breaking backwards compatibility](http://stackoverflow.com/questions/2875533/what-features-do-you-want-to-see-in-net-5-c-5/2876994#2876994) by automatically changing old code using `[Flags]` to explicitly number its enums
BlueRaja - Danny Pflughoeft
@BlueRaja: I'm not sure I understand. Old code with [Flags] already requires you to explicitly number your enumerates.
Randolpho
@Randolpho: I didn't know that - that makes this idea even better!
BlueRaja - Danny Pflughoeft
@BlueRaja: with any version of .NET right now, in order to implement a `[Flags]` enum, you have to write (excuse the collapsed syntax here): `[Flags] public enum MyFlags { Value1=1, Value2=2, Value3=4, Value4=8, /*etc.*/ }`. My suggestion is to have anything that's marked with `[Flags]` automatically enumerate on those values rather than require them explicitly, *unless* they are explicitly set. If they're explicitly set in old code, existing behavior would be unchanged.
Randolpho
@Randolpho: I understand that. *This idea* was referring to your idea.
BlueRaja - Danny Pflughoeft
But should the first value be 0 or 1?
Joe
@BlueRaja: Sorry; looks like miscommunication on my part. :)
Randolpho
@Joe: You bring up an excellent point; in a [Flags] Enum, you might want a 0 value flag to represent "Not Set". But sometimes you might not, if your Flags require a value. Hmm... not sure how to handle that for this feature request. First Enumerate, if marked with a "Default" attribute, gets zero value? Too complex... Argh, that's a monkey wrench. Well, I'll leave it for Microsoft to solve. :)
Randolpho
@eidylon: I thought I covered the concept of combinations in my post.
Randolpho
To avoid breaking existing code, this behavior to make this behavior optional : `[Flags(AutoFlags = true)]` (of course AutoFlags would be false by default...)
Thomas Levesque
@Thomas Levesque: excellent suggestion.
Randolpho
@Joe, @Randolpho - how about [Flags(Start=0)]
JBRWilkinson
Good idea. I would like to see set/clear flag metaphor too. I haven't thought of the syntax...perhaps myEnum.set newflag; myEnum.clear newflag;
kenny
But this way you can have _only_ 32 values per enum! What about if you wanted 4294967296 values! The horror!
Callum Rogers
@Kenny: I, too, would love to see standard set semantics for flag enums. As it is, I tend to go with a unique set of extension methods for each flag enum I create.
Randolpho
@Randolpho me too, save the keyboards!!
kenny
+10  A: 

Allow use of numeric operators in generic methods. I want to be able to do something like this:

T Add<T>(T a, T b)
{
    return a + b;
}
Gabe
Can you provide an example?
Aren
something similar was suggested here: http://stackoverflow.com/questions/2875533/what-features-do-you-want-to-see-in-net-5-c-5/2875827#2875827
Victor Rodrigues
What if T doesn't have an implementation for this operator ? For instance, DateTime + DateTime is not defined...
Thomas Levesque
@Thomas: There are several options for implementing this. One is to have an interface (perhaps `INumeric`) that numeric types implement (the same way they implement `IConvertible` or `IEquatable`). Another is to allow constraints like `where T: T op_Addition(T, T)`.
Gabe
How would this work if `T` was `byte` or `short` (`a + b` would return `int`)?.
Danko Durbić
Danko: There's also the issue of what to do when this happens inside a `checked` region.
Gabe
+17  A: 

Better stack trace line number information on exceptions thrown inside an object initialization block.

If I have a code using initialization syntax like the one below:

var someObject = new SomeObject()
{
    Prop1 = (int)variable1.SomeMethod(),
    Prop2 = variable2.SomeMethod(),
    Prop3 = (String)variable3.SomeMethod()
};

If an exception is thrown by the assigment

Prop2 = variable2.SomeMethod()

The exception thrown by the CLR (let's say, a NullReferenceException or an InvalidCastException) says on the stack trace that an unhandled exception was thrown at the line of the variable declaration instead of the actual line that caused the exception.

var someObject = new SomeObject()

So it is not possible to know exactly which line caused the exception without debugging.

Carlos Loth
That's a CLR feature, not a C# feature.
Billy ONeal
The question title is (at least _now_) for .NET 5 and C# 5.
Drew Noakes
+17  A: 

Provide a strongly-typed way to reference a property of a class without using reflection and without using the lambda syntax 'hack' that is all over ASP.NET MVC 2 "strongly-typed" helpers and is cropping up in more and more places, e.g. Entity Framework "strongly-typed" .Include statements.

Rather than picking apart Expressions to achieve strongly-typed access to properties of a class give us a way to reference and manipulate them directly.

Here are some examples of the kind of hacks people are doing today with lambda expressions: http://mattias-jakobsson.net/Item/36/Strongly%20typed%20include%20in%20EF, http://www.replicator.org/node/88

In MVC you can use the strongly-typed helpers like this: <%= Html.LabelFor(m => m.FirstName) %>. If you had a way to reference a property directly, let's call it '$' for the sake of argument you would write something like <%= Html.LabelFor(Customer$FirstName) %> or for a nested property <%= Html.LabelFor(Customer$Address$City) %>.

In EF you might write context.Customers.Include(Customer$Address).

Essentially this new A$B construct is a shortcut for typeof(A).GetProperty("B") but strongly-typed and with intellisense on B.

Also, perhaps, rather than returning the existing PropertyInfo type it would return a new generic PropertyInfo<A> so you can have a signature like LabelFor<A>(PropertyInfo<A> property) and still be strongly typed on the model type. And in this case you could omit A and just write LabelFor($FirstName).

[NB This has NOT been thought out totally, feel free to suggest a better way to avoid using lambda's to specify properties.]

Hightechrider
So `dynamic`, which is in C# 4? I'm confused here.
JulianR
Clarified that we want a strongly-typed way to do this (think refactoring). Using `dynamic` is no safer than using strings which is what the lambda syntax 'hack' is attempting to avoid.
Hightechrider
Can you give an example of what you think it could look like? I'm having trouble figuring out what you're looking for.
Gabe
@Gabe: When you want to reference *some* property of a class, but don't know what property ahead of time, you will use a `Func<object, myClass>`, and pass in a `(o => o.myProperty)`. This becomes a nuisance when you have to use it ALL over the place, like in MVC 2. He is asking for a different way to pass in a "reference" to a property.
BlueRaja - Danny Pflughoeft
So you want first-class properties?
Gabe
@Gabe - yes, see examples added (except that 'first class properties' has other meanings)
Hightechrider
I like using lambdas to specify properties. I just wish I could do the same with events. It'd make using Moq a bit easier.
Roger Lipscombe
Maybe it could be an analog of `typeof(T)` such as `memberof(Foo.Bar)`. It would return a `MemberInfo` http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.aspx
Drew Noakes
+1  A: 

__LINE__ and __DATE__ style preprocessor defines for build/version management in the source. I realize there are workarounds involving pre/post build steps and so forth but it would just be easier to have a built-in solution.

Ron Warholic
Never, no compiler macros. Those are so... evil. C# is nice because it's so clean and consistent.
Dykam
They are preprocessor defines, not macros in the C++ sense. C# already has several of these defines (DEBUG, TRACE...).
Ron Warholic
Those aren't constant replacements, but preprocessor directives, which only work in #if/etc.
Dykam
But a compiler-only constant that cannot be redefined surely doesn't bring the entirety of the 'evil' C++ macro system with it, no?
Ron Warholic
I feel it does. My concern goes mostly to the fact the barrier is lowered to bring in other constants. The nice thing about C# was that both compilers where fully compatible.
Dykam
+1  A: 

I saw someone propose multiple inheritance and I thought of something that might be less radical.

The concept might be a bit close to partial classes. I'm not familiar with the concept of mixin but a quick Wikipedia look seems to indicate that's what I'm thinking in.

Basically:

interface IXyz {
   void someFunction();
}

//implementations must always be associated with one interface
implementation CommonXyz : IXyz {
   void someFunction() { /* do something */ }
}

interface IAbc {
   void otherFunction();
}

implementation CommonAbc : IAbc {
   void otherFunction() { /* something */ }
}

public class MyClass : CommonXyz, CommonAbc {
   /* class content */
}

In many ways, implementations would be like abstract classes, but always associated with a single interface, no added functions(except perhaps private functions?) and supporting multiple inheritance.

luiscubal
You can do this already if instead of "implementation" you make an extension method on the interface.
Tesserex
+1. What you're describing might be called a "true" or "pure" mixin, which is basically a pre-implemented interface. It's a feature I'd love to see, but *can* live without.
Randolpho
@Tesserex: but recall that an extension method so does have access to the internal state of the object on which it's called. Presumably a mixin would.
Randolpho
@Tesserex: Not really. implementations would be optional. You could just implement the interface instead and define your own implementation. Unless we have something like virtual extension methods, which are a bit hard to imagine.
luiscubal
+92  A: 

switch syntax: smart case expressions and no more mandatory break statement

I'd like more smart/friendly syntax in switch statements. When the caseswitch is an integer, allow lists, ranges and expressions:

    switch (anInt)
    {
        case 1, 2: 
            Console.WriteLine("1 or 2");
            break;
        case 3..9:
            Console.WriteLine("3 to 9");
            break;
        case >= 10:
            Console.WriteLine("10 or higher");
            break;
        default:
            ...
    }

And for any other type, still allow the list syntax:

    switch (aString)
    {
        case "one", "two":
            Console.WriteLine("1 or 2");
            break;
        case "three":
            Console.WriteLine("3");
            break;
        default:
            ...
    }

Maybe even allow expressions that access members of the caseswitch:

    switch (aString)
    {
        case .IsNullOrEmpty():
            ...
        case .Length > 100:
            ...
        case .Contains("foo"):
            ...
     }

Furthermore, once the list syntax is implemented, the ridiculous mantatory break statement can be eliminated and always assumed, because fall-through wouldn't be needed.

(Actually, as far as I understand, break could be removed regardless of my suggestions. Since the only time we are allowed to omit break (indicating fall-through) is when there is no code in the case block, why doesn't the compiler just add it for us when we have code in the case block, and omit it otherwise?

The only time we should ever want to use break is to specify that we want a certain case to do nothing.)

Charles
FWIW, Visual Basic supports this syntax
Dustin Campbell
@Dustin Campbell: Really? Not bad, VB.NET. Not bad.
Randolpho
+1 for 0..n , really good way to describe a set of numbers. I like the other constructs also.
Victor Rodrigues
Hear hear! And also, remove the redundant "break" statement - why require code that doesn't actually do anything (since removing it is currently an error)?
BlueRaja - Danny Pflughoeft
@BlueRaja: Agreed; I hate the mandatory "break" too. If these enhancements were implemented, "break" could always be implied, since fall-through would never be needed. In fact, I will add that to my answer.
Charles
You say list, just reduce it to taking an doing `caseIEnumerable.Contains(switchItem);` and have the alternative syntaxes be generators. And for the expression, let the switch just accept expressions. This basically transforms switch into a tight if/elseif/else.
Dykam
Add to your string example `case .Length>10` and things like accessing properties. That'd be awesome as well.
Earlz
@Earlz: added your suggestion.
Charles
Yes VB.NET does support it. It is kind of in line with the above answer of if(x in (1,3,10)); if(x in (0..10)) and so on. Looks very elegant indeed
Shravan
You can actually do something similar with an extension method : http://pastebin.com/g3DZGZdK
Thomas Levesque
@Charles: Some of us actually *use* the fall-through of the case statement to break apart what might otherwise be an enormously long line of conditions we want to execute the same way. I think typing 6 characters is worth that amount of flexibility.
Billy ONeal
That last example doesn't make sense to me as a `switch`. You're checking `bool` values, not strings; so internally it would have to be something like `switch (true)`, which makes it clear the only way it could be implemented (internally) would be as an `if`/`else`. The whole purpose of `switch`, to me anyway, is to offer a more efficient option in cases where jumping to a specific location is possible -- but this entails certain constraints. VB.NET may support this syntax, but its `Select Case` (in scenarios like this) then degenerates into basically another way of just writing `if`/`else`.
Dan Tao
@Billy ONeal: you could still put each condition on a separate line if a list a conditions were allowed.
Charles
@Billy: [C# does not support implicit fall-through](http://msdn.microsoft.com/en-us/library/06tc147t%28VS.71%29.aspx) - `break` or `goto` is always required. The fact that you have not noticed that tells me that you've never needed to use it. Since `break` is by FAR the common case, and you should **always make the common case the default**, the `break` requirement should be removed. In the rare-case a fall-through is helpful, an explicit `goto` makes sense.
BlueRaja - Danny Pflughoeft
@BlueRaja: Yes it does; with the stipulation that there are no statements between the falling through `case` statements.
Billy ONeal
@BlueRaja: What about our friends whom come from languages supporting fall though. This would confuse the heck out of them. BTW, you can also use `return` or `throw` without the need of `break` or `goto`. Heck, another option would be to have the default be a `goto` so it act as a fall though. That would really make more since, but would be just as big of a mess and confusion.
Matthew Whited
So... basically the ideal switch would take `Func<T, Bool>` for the case where `T` is the type switched on.
Dykam
Personally, I'd like case fall-through :-(
Jess
+38  A: 

Enum classes (just like Java!)

I find it annoying many times when I can't assign whatever values I want to enums.
The restriction to number types is very limiting, and I feel the enum system in C# is very weak compared to Java's.

Basically, Java has enums that are classes.
They have constructors, fields, methods, everything. This is VERY useful.

Code example:

enum Direction {
   // This is the same as doing Right = new Direction(0,1), etc.
   Right(0, 1), Down(1, 0), Left(0, -1), Up(-1, 0);
   public int X { get; private set; }
   public int Y { get; private set; }
   // I has constructor!
   private Direction(int x, int y) {
      this.X = x;
      this.Y = y;
   }
   // I has methods!
   public Direction GetOpposite() {
       int opposite = this.Ordinal + 2;
       opposite = (opposite > Direction.Count) ? this.Ordinal - 2 : opposite;
       return Direction[opposite];
   }
}
Rubys
Well, both systems have their advantages. I like that `enum` in C# is usable as an `int` and as a flag, it's also very lightweight. You can also emulate both systems in both languages, in C# you would use a sealed class with a private constructor, but you won't be able to `switch` on it. In Java, you would use `static final` ints, but you won't be able to restrict it to valid values only.
JulianR
+1000, enums are one of the few features Java got right and C# got wrong. @JulianR: Java enums can be used as both an [int](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Enum.html#ordinal%28%29) and a [flag](http://java.sun.com/j2se/1.5.0/docs/api/java/util/EnumSet.html) as well.
BlueRaja - Danny Pflughoeft
Nice... I had no idea you could do that in Java
Thomas Levesque
I don't see the point, you can use a class if you need methods. And enum is a enumeration of values! Java does it wrong IMHO.
Ion Todirel
@Ion: I dare you to write a class for 4 directions compatible with what I typed above that would be even close to how concise what I wrote is.
Rubys
@Rubys, I can't see how this is any better than a struct of similar extraction. Yes, you save some characters when coding, but it is really any different?
Alastair Pitts
@Alastair: Look around you. Half these suggestions are already in existence, and the improvements are basically syntactic sugar. BY that logic, you should write everything in ASM, since everything else is syntactic sugar. Syntactic Sugar = Abstraction.
Rubys
@Rubys, a fair point, but I still wonder about the relative worth of the extra features of an enum. Still, it's a well thought out idea, I'm just not personally a fan,
Alastair Pitts
No thanks. Just looking at the code you posted I have no freeking idea what's going on. Keep enums simple.
gmagana
You can do pretty close to this with immutable (semi-)singleton objects as members of a static class.
kyoryu
You can give extension methods to `enum`s. This is just a workaround for one of the things you're asking for, but it comes in pretty handy.
Matthew
the example cited doesn't do the concept enough justice. it's nice to be able to assign arbitrary properties to an enum. my favorite example thus far (as i work in telecom) is bandwidth. I can have an enum defined that has both the description and the rate in bits by doing something like: public enum Bandwidth { E1 ("E1", 2048000L), T1 ("T1", 1544000L) ... }i've found it missing from time to time. sure i can 'work around' it but it just feels so right in java
dovholuk
A: 

For .NET in general, perhaps some sort of native expression evaluator. Perhaps even a native scripting system. Like the VBScript/JScript COM object that would interoperate with your own .NET variables.

(There are currently third party components and other tricks to evaluating expressions in .NET)

+12  A: 

Most replies here have been about C# features, but there is one relatively simple feature I would love to see in the .NET libraries. A control that exposes the file system identical to what you get on the OpenFileDialog or SaveFileDialog controls. I regularly need to provide the ability to open or save a file to/from disk and at the same time provide some control over the operations. Now this usually becomes one dialog for making selections (sometimes just a checkbox or two would be enough) and then the save dialog opens form there. It would be great to be able to simply create a custom dialog with the settings I need and a file selection control. Similarly a simple way to customize the PrintDialog would be great too.

David
But these FileDialogs, they arent a part of the .Net framework but wrappers around what the underlying OS provides. So IMO this wouldn't be possible, since you won't know in advance what settings of the FileDialog you could manipulate, besides the most basic like which folder to start in, file patters, allowing multiple selections and things like that.
BurningIce
I meant simple from an end-user perspective, not simple for MS to implement. Of course it's possible, there's probably a number of ways the equivalent functionality could be exposed. Whether there's enough demand for MS to put in the development effort I don't know, I was only voicing my desire for having it...
David
+4  A: 

The ability to use reflection to access the runtime values of parameters passed to a method.

For example:

public static bool VerifyXPath(string i_strXPath, bool i_bIncludeXPathPrefix)
{
    Log.Instance.EntryFormat("i_strXPath: {0}", i_strXPath);
    Log.Instance.EntryFormat("i_bIncludeXPathPrefix: {0}", i_bIncludeXPathPrefix);
    // etc.
}

could become like this, allowing the method signature to change without having to update the logging statement:

public static bool VerifyXPath(string i_strXPath, bool i_bIncludeXPathPrefix)
{
    Log.Instance.MethodParameters();
    // etc.
}
Simon Chadwick
That would be very cool, but unfortunately I do not think it will every happen since it pose a security risk to allow code to walk the stack to inspect values.
Brian Gideon
Um, you can already walk the stack.
Joel Coehoorn
@Joel: Do you have a reference to an example of doing this?
Simon Chadwick
@Simon - sorry, I meant to reply to Brian's remark. You can already walk the stack via `System.Diagnostics.StackFrame/System.Diagnostics.StackTrace`
Joel Coehoorn
@Joel: The StackFrame and StackTrace classes cannot resolve runtime method parameter values, as far as I know. If you have an example to show otherwise I'd be really grateful.
Simon Chadwick
+19  A: 

Static extension methods

and

Static abstract methods

Tesserex
What problem do static extension methods solve? It's too easy to find what source file methods are defined in?
BlueRaja - Danny Pflughoeft
The same problem that non-static extension methods solve. What if I didn't write the original class? A common example is DateTime.
Tesserex
Yes, static extensions would be good. It would greatly improve discoverability. I've seen way too many `MathUtil` classes.
JulianR
"Static abstract methods?"
@MaxGuernseylll: That's got me scratching my head too.
Randolpho
+1 for static extension methods. I'd love to add some methods to System.IO.Path.
Roger Lipscombe
static abstract methods? How is that supposed to work?
bitbonk
I guess it sounds totally not useful because static defeats the purpose of inheritance. But I came upon a situation where I could have used it. It would really only come into play if you had a generic that said `where T : AbstractClass` and then you called `T.StaticMethod`. Other than that, I guess it's kinda dumb.
Tesserex
The Static abstract would be pretty cool. But it would require changes to the CLR. It could give you a way to generically use the `.TryParse` and similar methods.
Matthew Whited
+21  A: 
  1. A tool for converting old code to .Net 5, so Microsoft can fix a bunch of problems with the framework without breaking backwards compatibility (MS Connect)

  2. Move all those helpful methods from List<T> to IList<T>... using extension methods! (This keeps the interface simple to implement, while allowing users of ILists access to all the useful List<T> methods) (MS Connect)

BlueRaja - Danny Pflughoeft
A: 

API Changes
One thing that would be good would be a change in the APIs.
Many of the functions that .net is built upon are wrappers for WIN32 and WIN16 APIs.

Network Changes
Although System.Net is plenty powerful, there are many aspects of it(such as sync vs async transfers) that make development cumbersome. Maybe a wrapper around it or just making it simple to use and plug into any application.

Feature Parity of All Languages
For School, I started off in VB.net and now am a C# Coder. VB has many features that C# doesn't have and vice versa. Feature parity would definitely help. I understand that each language wants to have their own thing and that is fine. EG. VB had optional methods and so on but eventually, features need to make their way into all languages.

Feature Parity of WPF/Silverlight
Silverlight is a great platform and same with WPF. However, there are key differences that make interop and keeping a same codebase a hassle. Extending Silverlight is definitely something they need to do.

A smaller framework
Although the new framework is smaller than the older ones. They still bog the download up. Having the next framework, not only smaller but compressing the rest would help. For example, to have .net 4, it is 2+3+3.5+4, so if 4 is smaller it helps but making the older frameworks smaller would also help.

Single Framework Install
I found that installing .net Framework was a hassle on my old xp machine. I had to go one at a time, 3 then 3.5 then 4. Maybe one download that installs all of the frameworks at once would help.

AKRamkumar
Regarding your first two suggestions: API changes and networking changes are already taking place. That's what WPF and WCF represent! The next three are excellent points, but I think Microsoft is already working on some of them; with each release the differences between VB.NET and C# get smaller, ditto WPF/Silverlight. A single framework install and a smaller framework are both laudable goals.
Randolpho
They are working on feature parity.
Dykam
this answer belongs on super user :)
Earlz
you don't need .NET 2 through 3.5 to have 4.
Sekhat
@sekhat I think he means if you want to be able to run any .NET app built on any version you need to install 1.1, 3.5 and 4. Obviously not so much of an issue in vista and 7 as they have some framework versions already installed.
PeteT
+2  A: 

An implied "new" type, so that

List<ListViewItem> listLVI = new;

means the same as

List<ListViewItem> listLVI = new List<ListViewItem>();
Simon Chadwick
we already have var for this, but on the other side of the `=` :)
BlueRaja - Danny Pflughoeft
I do still like this idea a bit. But var is more flexible.
Dykam
Or: new List<ListViewItem> listLVI { .. initialization .. };
m0sa
VB actually has type-inference now, and the initialization bit too that m0sa lists. This sounds like you would benefit if they would just port this from the VB compiler... In VB you would do (VERY simple and somewhat useless example): Dim li = New ListItem With { .Text = "Hi there!", .Value = 0 }
eidylon
then someone would inevitably write `var blah = new;` :)
RCIX
and what would happen if you wroteIList<ListViewItem> listLVI = new;
BurningIce
@BurningIce - It wouldn't compile. Simple. Though I agree that if you program against interfaces, which is usually recommended, then this feature wouldn't be terribly useful.
ICR
@RCIX:he will have a dynamic.but how about this:List<int> a(10);
Behrooz
+38  A: 

Operator Constraints with Generics

An often suggested feature is to add a Number interface to numeric types so you can use arithmetic in generic methods. I don't think that quite feels right. But numbers do already share an interface of some sort: operators.

Why not this:

public static int Sum<T>(IEnumerable<T> seq) where T : operator(T=T+T){ .. }

This would even work for your own types, like vectors or matrices, or even DateTime and string (but that last one would be a bit non-idiomatic).

Constructor Constraints with Generics

When I found out you can constrain to new(), I was really surprised that you couldn't constrain to for example new(int, string). And I've definitely had use-cases where this would have been really useful.

Expanded Support for Dynamic Typing

While some might argue that it would make C# just more complex, I don't think it would. I really don't see any reason why full-blown static and full-blown dynamic typing can't exist side by side, where you use the one that makes sense in the current situation. I think while it would make the language more complex in terms of number of constructs, it would simplify the usage of the language. I've been doing dynamic typing ever since I first started using C#, it's just that I've been using reflection for it. I'd say by far most of my uses of reflection involve getting late binding capabilities, why not integrate it more into the language?

And when I mean expanded support, I would like the language to expand on the current dynamic, which is a good start, but not quite there yet. I would like to have something more like JavaScript, so I could say:

dynamic obj = new Foo();
int value = obj[aVariable].Method();

But that is not possible at the moment unless type Foo implements the right interfaces.

Currently, this would take:

var obj = new Foo();
object temp = obj
           .GetType()
           .GetProperty(aVariable)
           .GetValue(obj, null);

int value = (int)temp          
            .GetType()
            .GetMethod("Method")
            .Invoke(temp, null);

Awful and painful.

JavaScript-style dynamic object literals

Another nicety would be the support for object literals. The new { Foo = 1, Bar = "string"}; is nice, but it generates a class with readonly properties, when sometimes, I want to change properties or even add new ones. And like I use reflection to have late binding, I have used many Dictionaries to support just that.

Instead of:

var dict = new Dictionary<string, object>
{
  { "Foo", 1 },
  { "Bar", "string" }
};

dict["Foo"] = 2;
dict["NewProperty"] = Something();
dict["Bar"] = "a new value";

I would like to see:

var obj = new dynamic
{
  Foo = 1, 
  Bar = "string"
};

obj.Foo = 2;
obj.NewProperty = Something();
obj["Bar"] = "a new value";

And sure, the above Dictionary example is pretty clean, but usually you can't use the object initializer syntax.

Another use-case for this is when using LINQ to SQL, say you have this:

var customers = (from c in context.Customers
                 select new
                 {
                  c.Name,
                  c.ID,
                  Foo = FunctionThatCantBeTranslatedToSQL()
                 }).ToList();

That crashes because you use a function that has no supported translation to SQL.

So you need to do this:

var customers = (from c in context.Customers
                 select new
                 {
                  c.Name,
                  c.ID
                 }).ToList();

var result = from c in customers
             select new
             {
               c.Name,
               c.ID,
               Foo = FunctionThatCantBeTranslatedToSQL()
             };

It's really painful when you select 10+ columns from the database, and you need to repeat them all just because you want to set one new value on the object, for whatever reason.

Why not just:

var customers = (from c in context.Customers
                 select new dynamic
                 {
                  c.Name,
                  c.ID
                 }).ToList();

customers.ForEach(c => c.Foo = FunctionThatCantBeTranslatedToSQL());  

The whole new dynamic construct could just be syntactic sugar for:

dynamic obj = new ExpandoObject();
obj.Foo = 1;

Null Safe Member Operator

Instead of doing:

var obj = Foo();
Bar value = null;
if(obj.Bar != null && obj.Bar.Something != null)
{
  value = obj.Bar.Something.DoSomething();
}

You can do this with Groovy's null safe member operator:

var obj = Foo();
var value = obj?.Bar?.Something?.DoSomething();

Easier Immutable Types

This is a hard one.

Currently, one way to do immutability is to use a wrapper like ReadOnlyCollection<T> and wrap an ICollection<T> with it. And much like Nullable<T> is a wrapper around a value type to support "null" values, why not introduce a language construct that automatically generates wrappers like ReadOnlyCollection<T> in a very simple way?

class Foo
{
  public int ID { get; set; }
  public string Name { get; set; }
}

..

private Foo# _member;

public Foo# Something
{
  get
  {
    return _member;
  }
}

Foo# would be a distinct type from Foo and just compiler magic for an automagically generated class.

Of course, the question is, what does Foo# look like exactly? Does it only expose automatic properties like in Foo by making them get only? Because if it also exposes normal properties and methods, there's no guarantee that they don't change the object.

I have no idea, honestly. But I thought the concept was interesting.

Mono.Simd

It would be nice if .NET 5 had something like Mono.Simd, providing auto-vectorization for certain types, or preferably by decorating types with special attributes. But that last option sounds very hard, I don't know if it's possible at all. Just highly optimized Vector and Matrix types that utilize SIMD units of CPUs would be most welcome.

Nested Iterators

As described in this paper by Microsoft researchers, a proposal for a more efficient and simpler way to iterate over (among others) recursive structures. I'll admit that I don't understand the paper, but I do know the proposal will improve the following scenario:

public override IEnumerable<int> Foo()
{
  yield return 1;
  yield return 2;
  foreach(var i in base.Foo()) yield i;
}

By allowing me to write:

public override IEnumerable<int> Foo()
{
  yield return 1;
  yield return 2;
  yield return base.Foo();
}
JulianR
For the someDynamic[foo] syntax, where foo is a string, you can implement dynamicobject yourself to implement this ;).
Dykam
I know, but *I don't want to do that*. In fact, often, I can't, because I didn't write the class. It would just be an alternative to the ugly and complicated `obj.GetType().GetProperty(aVariable).SetValue(obj, null)`.
JulianR
But there is no default dynamic implementation. And the one you my be implying, is in the DLR, which is Open Source ;)
Dykam
Have a look at `AsEnumerable`; it eliminates the need for your `ToList` call.
Gabe
+1 for generic operator constraints! Missed those a few times.
cwap
+1 for easier immutable types! Creating an immutable value type, even something as simple as wrapping String, requires a ton of boilerplate. This is one of the rare areas where C++ is actually *easier* than C#.
kyoryu
You should split your suggestions into separate answers, because currently there is no way to vote for them separately
Thomas Levesque
+5  A: 

Generic attributes...

Arnis L.
A: 

The ability to merge a pdb file into its related dll or exe assembly for a debug build.

This is so that we don't have to deploy all the corresponding pdb files with a set of assemblies. This would be especially useful for debug assemblies placed in the GAC, so that symbol and line number information are available when exceptions are thrown in GACed assemblies.

Simon Chadwick
+1 for this simple and powerful idea.
@MaxGuernseyIII, @Simon: I don't see the added value of this. There is nothing you couldn't do already now with separate .pdb files. In fact, merging an assembly with it's debugging information will make the assembly larger which will possibly have an impact on performance/memory efficiency.
0xA3
This is a CLR feature, not C#.
Billy ONeal
@Billy: Yes, but the question title also says ".NET 5", not just C# 5.
Simon Chadwick
@0xA3: Yes, you are right, it would not add functionality, but that is not the point. Separate pdb files are a hassle to deploy, especially with system using dozens of assemblies, and a huge hassle if these are GACed. Performance and efficiency are not primary issues with many QA and test deployments anyway, in which systems are being validated and run through regression test suites.
Simon Chadwick
I've never had any problem deploying PDB files when needed. msbuild spits them out easily enough when you ask for them. What's your build/deploy process?
Drew Noakes
@Drew: What about assemblies deployed to the GAC? How do you deploy the PDB files in this case?
Simon Chadwick
@Simon. Fair point. I avoid the GAC whenever possible for many reasons. Now I have yet another :)
Drew Noakes
+14  A: 

The ability to handle long file paths in System.IO

This has been a problem for a long time. I know it's not easy but it should be addressed.

Dan Blair
Andrei Taptunov
+22  A: 

First-class events

I want to be able to pass an event to another function so that other function can subscribe or unsubscribe from the function.

That way I could write

Observable.FromEvent(tree.MouseMove)

instead of

Observable.FromEvent<MouseEventArgs>(tree, "MouseMove");

My suggestion is shorter, typesafe, safe for refactoring, and makes the implementation of FromEvent much simpler. It's also much easier to use than the third alternative,

Observable.FromEvent<MouseEventArgs>(handler => tree.MouseMove += handler,
                                     handler => tree.MouseMove -= handler)
Gabe
In VB you can define a function that accepts as one of its parameters a delegate/function-type and then pass in the address of any function (or sub) whose declaration matches that delegate-type.
eidylon
@eidylon, in C# too... that's not the point of this suggestion.
Thomas Levesque
But anyway, I'm not sure how this would be useful...
Thomas Levesque
@Thomas Levesque: Are you familiar with the Reactive Framework? This is one of the most common use cases for Rx.
Gabe
Ah, OK. I reread it a little more closely and see what you're talking about. This is kind of the reverse case of the whole delegate method. It is an interesting concept... not that it would be practical, and would probably be slow, but from a purely theoretical POV, I wonder if this couldn't be done now with Reflection. If it is only needed for a rare, weird case, maybe that actually would be acceptable depending on the circumstances.
eidylon
eidylon: Maybe a year ago it was a rare, weird case. However now anybody using Rx with events (i.e. anybody using it in their UI) will have their code littered with this stuff. Reflection is indeed how this is currently implemented, but a clean, natural implementation is much preferred.
Gabe
Even better would be completely decoupled events, like offered by CAB (Composite UI Application Block)
BlueRaja - Danny Pflughoeft
+42  A: 

A better way of dealing with null class variables. Or basically an expansion of the ?? operator.

For instance I'd like to see

MyClass value=null;
int something=value.x.y ??? 0; //notice the 3 question marks
//something is now 0

This would make it so if anything in the expression value.x.y is a null reference then it will default to 0 as denoted by the ??? operator.

Earlz
That'd be really awesome! Would love to see that in the VB compiler too!
eidylon
That's a really good idea! +100000
BrunoLM
The only possible problem I see with this is if reading a value from a property changes some kind of state. I have no idea what kind of idiot would do such a thing, but it is a possible problem
Earlz
Note this is the same suggestion as "lifting member access to null".
codekaizen
@codek I'd say it's only related. (I read that before posting) His idea is more that `value.x.y` would resolve to null (which would throw an error) mine suggests controlling the default. His method plus `??` though would be exactly my method. I think mine is a bit less radical and more of a "opt-in" approach, which I like because non-obvious possible null references are evil
Earlz
seems better than Null Safe Member Operator
Michael Buen
Nice idea, much better than the .? suggested operator.
erikkallen
It's a good suggestion. The only problem is that `value.x.y ??? 0` and `value.x.y ?? 0` mean two very different things, are both valid, and differ by only an easily missed character repetition. Perhaps with different syntax?
Andrew Russell
@Andrew yea true I was thinking of that myself.. Possibly make use of the rarely used `$` character? Like `value.x.y $? 0`
Earlz
@Earlz perhaps a keyword would work nicely. `value.x.y otherwise 0`?However I've spotted a potential design flaw - what if you want the value for `y` even if it is null? Perhaps a solution would be to have `otherwise` to check just `value.x` for null, and `otherwise ??` to check `value.x.y`. Although this is starting to get a little messy.
Andrew Russell
Not sure this is as good as `?.`. What about `if (a?.b?.c==null) { ... }`? You'd have to write `if (a.b.c ??? null == null) { ... }`
Drew Noakes
@Drew I think they are similar features that would complement each other. So both being implemented would be awesome
Earlz
`?!?` would be so much more awesome. Anyhow, I giggle at the idea that as C# progresses through it's versions, you might eventually find operators like this, such as `:)`, `:(` `?!??!` or `<('.'<)`...
Dynami Le Savard
@dynam Yea maybe `?!` would be nicer.. but can't use `?!?`.. It's a trigraph in original C (I hope C# doesn't inherit that bit!) which could confuse some people
Earlz
@Earlz well, just tested it and `var res = nullableBoolean.HasValue ?! nullableBoolean : true;` compiles, as it interprets it as `.. ? !nullableBoolean` :(, so no can do on `?!`
Dynami Le Savard
@Dynam ah, yea I guess thats true. How about `!?`
Earlz
this is going to go lisp.
Behrooz
A: 
JoeBilly
if this were implemented `object myObject = Foo();` should not be allowed **at all** it should give an ambiguous error in the same way that ambiguous namespaces do.
Earlz
This also could cause quite a bit of havoc with the recent type-inference feature added in to VB.NET 3.5.
eidylon
@Earlz: Yep I was thinking about this like I did for parameter based overloading, updated ;)
JoeBilly
The first is not possible without having the mechanism forcing reading the result. Without it there is no difference (on call) between procedure and function.
macias
Actually this is legal in CIL. It's not legal in any high-level .NET language, however.
Billy ONeal
+1 … why the downvotes? Other languages do this quite happily. Java at least can infer generics based on the return type. Why not .NET?
Konrad Rudolph
+7  A: 

I want my local static variables like in good old C++.

Developer Art
This is definitely a thing I miss. static class variables seem like a hackish workaround to me.
Earlz
@Earlz: a small correction: the work around for local static variable is not static class variable, but instance variable.
Codism
I'd love a variation: `void f() { member int i = 10; ... } `, which would make i behave like C++ static variables, but live as a member instead (and thus be initialized for every instance on the first call to `f()` for that instance).
erikkallen
Yep. I agree with this.
Brian Gideon
erikkallen: this is too unorthodox to be accepted, but yeah, I can't count the times I've wanted it.
Stefan Monov
+1  A: 

Overloading the assignment operator. I know it can be (greatly) abused but I had a project where this would have helped enormously.

Rodrick Chapman
Are you talking about implicit operator? http://msdn.microsoft.com/en-us/library/z5z9kes2(VS.71).aspx
bloparod
@bloparod - Not exactly. The problem with implicit is that it creates a new object. Basically I want a non static version of the implicit operator.
Rodrick Chapman
Could you give an example of when this would be useful?
Drew Noakes
A: 

Chained constructors. For instance I almost always end up having constructors where default values would be used.

For instance to have like

class Foo{
  public Foo(int bar,int biz){}
  public Foo(int bar){
    int defaultBiz = 0;
    if (bar > 20) defaultBiz = 2;
    Foo(bar, defaultBiz); //illegal currently
  }
}

If this were legal then I wouldn't have to go about creating dumb looking Init methods for doing just this.

Earlz
You can already do something like that: `public Foo(int bar) : this(bar, DEFAULT_BIZ) {}`
Roger Lipscombe
VB allows you to do this, I've used it regularly. I can sympathize if you don't have this! Though if VB has it i would think it should be relatively simple to port to C#.
eidylon
@Roger Lipscombe: But then that code is run *before* the code in the constructor your declaring, which is sometimes undesirable.
RCIX
+5  A: 

Do ASP.NET features count? Generic controls without having to resort to ControlBuilders.

<my:EnumDropDown OfType="MyEnum" runat="server" ID="DD" />

And then from code-behind:

MyEnum value = DD.SelectedValue;

I'm not to picky about how exactly the markup to include the generic type would look as long as it's SGML compliant. This: <my:EnumDropDown<MyEnum> runat="server" /> is just ugly.

David
This would also be superb for ie. repeaters and other databound controls. Being able to write <asp:Repeater OfType="MyType" runat="server" ID="DD" />and then have the DataItem of Container be of MyType would be such a relief. Then you could write <%# Container.DataItem.SomeProperty %> instead of <%# ((MyType)Container.DataItem).SomeProperty %>
BurningIce
What about X<Y<Z>>?
luiscubal
+11  A: 

Some way to confirm that a chain of properties isn't going to throw a null at some point:

// Not good if Property3 throws an exception
string s = someVar.Property1.Property2.Property3.Property4;

Something along the lines of:

string s = ResolveNulls(someVar.Property1.Property2.Property3.Property4);

Which the compiler would expand to:

string s = (someVar != null && someVar.Property1 != null && someVar.Property2 != null && someVar.Property3 != null) 
    ? someVar.Property1.Property2.Property3.Property4 
    : null;

I'm not sure my weird function is the right implementation, but I absolutely detest writing out check statements like the lower example, because it's never very readable and always error-prone.

David
very much related to my answer http://stackoverflow.com/questions/2875533/what-features-do-you-want-to-see-in-net-5-c-5/2877385#2877385
Earlz
The only thing I'd add to your function would be a second parameter to allow the code to specify the default value that should be returned, should the evaluation of the properties throw the null error.
eidylon
@Earlz: Agreed - I like your ??? operator a lot! Also takes care of @eidylon's comment to control the value returned.
David
I'm going to have to write you a ticket for violating the Law of Demeter here. It's generally not good practice to be going that deep to reach something.
Secret Agent Man
Who says I wrote the code whose value I'm trying to access? ;-)
David
A: 

I would love to see a 'swap' OpCode for IL that takes the top two items on the stack and swaps them. I use a dedicated 'swap' local slot to achieve this for my ladder logic compiler, but the code would be cleaner with a swap OpCode.

Dan Bryant
Since a swap opcode would be implemented this way internally, why does that matter?
Billy ONeal
It doesn't really matter, though I'm thinking the jitter might be able to optimize a swap operation in various ways, depending on context. Perhaps it's already smart enough to recognize a local slot swap and optimize that, anyway. In some instances, a swap operation could be as simple as modifying the way a subsequent instruction is jitted, so that it uses the items in a different order (perhaps swapping the register references in some eventual x86 instruction.)
Dan Bryant
Remember: CIL is not machine code. It is just a way to **specify** programs.
SealedSun
@SealedSun, Yes, but IL is designed to be a compact way to specify a program for efficient compilation by the jitter. Undoubtedly the design of IL was informed by the requirements of the various jitters, so as to allow them to efficiently compile and optimize the code. It's not sufficient to merely specify the program; IL must also specify in a way that's efficient for jitting.
Dan Bryant
+32  A: 

Extended generic new constraints, for example: new(int, int, string)...

Forcing generic type argument to have a constructor with these parameters.

LexL
Could be tool with named/typed parameters as well. Or maybe allow interfaces to declare required constructors. (Of course this may require a change to the CLR so it would probably never happen.)
Matthew Whited
A: 

For quick, one-off, demo, or tutorial purposes, it would be great for the C# compiler to infer a default class, default Main entry point method, and common namespaces (System, etc.). It already infers a default app namespace.

So

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(fact(10));
        Console.ReadLine();
    }

    static int fact(int n)
    {
        if (n == 0)
            return 1;
        else
            return n * fact(n - 1);
    }
}

could be written as

static int fact(int n)
{
    if (n == 0)
        return 1;
    else
        return n * fact(n - 1);
}

Console.WriteLine(fact(10));
Console.ReadLine();

Wouldn't it be great to be able to test things like formatting output using a one-line C# program like

Console.WriteLine("{0,10:0,000.00}", 234.8989);

without having to decorate it with a class and Main method?

Simon Chadwick
I think this should just be extended into an official supported interactive C# shell
Earlz
You should have a look at http://www.mono-project.com/CsharpRepl
0xA3
There are a few videos of Anders showing something like this (C# REPL) about on the web. Looks like a runtime compiler lib is on their TODO list for 5.0.
Drew Noakes
@Drew: Thanks for the info!
Simon Chadwick
@Simon this question http://stackoverflow.com/questions/2210734/what-is-the-state-of-the-c-compiler-as-a-service has some good info and links, especially the one about the C# REPL being available today in Mono. So it seems that you can already do what you want, on Mono at least.
Drew Noakes
+3  A: 

I see a lot of requests for small syntactic sugar, and for some bigger changes that build on top of what's there.

I'd like to go the other way: more general features that could have been used to implement existing language functionality. Because the only way it's going to get more expressive for programmers is if you build functionality into the language that lets us do what Microsoft themselves are doing. Adding individual features is a +1, but adding features that let us add features is a *2.

On that note...

  1. Conditions. They're more general than exceptions, and could also be used to implement yield. But there's lots of other uses for them. Debugging would be faster and more fun!

  2. Reader macros (but simplified). I don't know exactly what form this would take, but I see a lot of requests for more terse tuple literals, range literals, and so on. I think a regex literal would be great, too. Why does every object I create need to come from new MyTypeName(...) or MyTypeName.MyStaticMethod(...)?

It wouldn't really matter if they turned around and declared that existing functionality was implemented using these (though it might be nice!). And no, I don't expect these -- the question was what do I want, not what I expect. :-)

Now I'll sit back and await all the comments that say this would only be abused, would make reading code ambiguous, make it harder for bad programmers, require taste to use well, can be easy to use but complex to define, and isn't all that important anyway -- all complaints that were just as valid for every version of C# ever shipped!

Ken
Honestly, if you want lisp you know where to find it.
Logan Capaldo
Logan: In the 1980's, that was the response to asking for GC. In the 1990's, that was the response to asking for OO. In the 2000's, that was the response to asking for simple metaprogramming. Maybe in the 2010's it'll be the response to asking for conditions? :-)
Ken
+2  A: 

I'd like to see a modules implementation for C#, something similar for what we have in Ruby.

Sometimes inheritance is not the best way to share code between classes and keep things DRY.

module A
{
    private void MA1()
    {
        //...
    }

    private void MA2()
    {
        //...
    }
}


module B
{
    public void MB1()
    {
        //...
    }

    public void MB2()
    {
        //...
    }
}

class C
includes A, B
{
    public void MC1()
    {
        //...
    }
}

So we could do:

var c = new C();

c.MB1();

and so on.

Victor Rodrigues
cant you do this with Interface?
BerggreenDK
the difference is that MB1() implementation only needs to be in B. When C includes B, it takes all methods. In ruby this has more features, because of the dynamic environment. There we can do something like "include ErrorLogging", and all methods that throw an exception can have an automatic error handling that stores a log, for instance.
Victor Rodrigues
seems like static methods covers this pretty well, but the proposed module does reduce the typing.
kenny
The difference between modules in Ruby and interfaces is that modules can actually define functions and describe state. It just happens to be methods/state independent of whoever needs to use them.
Matt
For any C# devs who are curious about this and don't know Ruby, Ruby calls this a mixin. Read more here: http://juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/
Drew Noakes
+1  A: 

Native enum support in Linq to Entities:

var inventoryItems = item in Items where Item.ItemType == ItemType.Inventory select item;

+9  A: 

It's a little thing, but inline declaration of a variable to be used in an out parameter when using a function. I often find it annoying to have to go outside the function call to declare a variable that does not get set to anything. The existing way you have to do is this:

List<int> list;
myClass.TryGetList(out list);

You could shorthand it to something like

myClass.TryGetList(out List<int> list);

There are no scoping issues with the declaration because even if you are using it in an if block the scope is not inside the if (or you can compile the IL to make it that way).

It's a subtle change that would just make it easier when I'm in the middle of writing a method and realize I need an out parameter. It's also really useful when there is an out parameter that you just don't care about (yes I do realize that's an API problem, but it does happen).

Craig Suchanec
On a similar note, I'd also like to be able to write something like this: `while ((int bytesRead = reader.Read())!=0) { ... }`.
Drew Noakes
+31  A: 

Weak delegates, to make it easy to implement weak events. A modifier like ~ could mark a normal delegate as weak :

public event EventHandler StrongEvent;
public event EventHandler~ WeakEvent; // Shortcut for WeakDelegate<EventHandler>

Note that a weak delegate would have to hold a weak reference to the delegate's target object, not the delegate itself (since we usually don't keep a reference to new delegates when subscribing to an event).

When invoked, the method would be called only on live objects, and delegates with "dead" target objects would be dropped from the invocation list.


EDIT : in response to Julien's comment, here's proof that a WeakReference on a Delegate doesn't work (or to be more precise, doesn't work as expected) :

var foo = new Foo();
var wd = new WeakReference(new Action(foo.Bar));
Console.WriteLine(wd.IsAlive); // true
GC.Collect();
Console.WriteLine(wd.IsAlive); // false

Since we didn't keep a strong reference to the Action delegate, nothing prevents it from being collected, even though foo is still in scope.


EDIT: moved the suggestion about indexed properties to another answer

Thomas Levesque
I don't get the point of #2; can't you just expose a string[]?
RCIX
What's the use case for indexed properties?
Gabe
@RCIX, no, definitely not ! If you do, client code could modify the content of the array, and you wouldn't know it. @Gabe, I don't have a specific use case in mind... I often use indexers, but sometimes I'd like to provide indexed access to more than one private collection
Thomas Levesque
@Thomas Levesque: You can do the indexed properties thing today. Simply create a new type overloading Operator[], and make your property readonly of that type. The property can now be indexed, and you didn't need any extra fun framework features to support it either.
Billy ONeal
@Billy ONeal, that's precisely what I *don't* want. That's not an indexed property, that's a normal property returning an object with an indexer. It's easy to do, but it's a pain to implement...
Thomas Levesque
I like the first one, I'm far from sold on the second one.
Doug McClean
Weak delegates exist today. `new WeakReference(myobj.MyFunc)` will result in a delegate that will leave as long as `myobj`. I'm currently doing this today to implement weak events. However, `new WeakReference(staticfunc)` though does not work as it is released almost instantly.
Julien Lebosquain
@Julien, I tried that before, and it doesn't work : the delegate is collected too early (before the target object goes out of scope). See my updated answer for an example
Thomas Levesque
+95  A: 

How comes nobody has yet mentioned non-nullable reference types?

string! nonNullable = someFunctionThatReturnsAString();

which would make the compiler say: "Cannot convert string to string!, an explicit conversion exists".

erikkallen
Oooh this would be neat!
Earlz
I dunno, you wouldn't be able to declare one of these without assigning something to it. Certain things would be very awkward.
Blorgbeard
On the other hand, being able to declare these for parameters would be absolutely wonderful. No need to be checking incoming parameters for null all over the place.
Secret Agent Man
I can not imagine at the moment what consequences this would have, but this is an intriguing idea.
Marcel
@Blorgbeard: Sure you would, but you have to initialize it before you use it ("use of unassigned variable foo"). There could also be some rule that all constructors must initialize all fields of non-nullable referenece types.
erikkallen
@erikkallen oh yeah, of course. Ok, this is an interesting one.
Blorgbeard
this would be great. it's nice not caring about null in Haskell / OCaml, so it'd be great in C# too.
Claudiu
I don't think this would play nicely with structs. For example, I don't see a (good) way that a `string!` could be a member of a struct. Also this could quickly lead to a similar cascading mess like const correctness in C++, yuck!
Andrew Russell
You can support non-null ref types via a struct abstraction, as in my Sasa library:http://sasa.svn.sourceforge.net/viewvc/sasa/trunk/Sasa/NonNull.cs?view=markupSyntactic sugar would be nice though.
naasking
@Andrew: Sure it would cascade, that would be the nice thing. The compiler will find more and your tests have to find less. Whenever it gets out of hand, insert an explicit cast (which might throw a NullReferenceException).
erikkallen
@naasking I hate to burst your bubble, naasking, but`NonNull<string> blah = new NonNull<string>(); Console.WriteLine(blah.Value.ToString());` throws a NullReferenceException.
Andrew Russell
@erikkallen I think at that stage you're just pushing the location of the NullReferenceException around - minimal gain for the extra effort. It would be far better to make checking for null easier in the first place (and there are a few suggestions for that in other answers).
Andrew Russell
@Andrew: Sure you just move it around, but it becomes apparent from the method signatures whether they can return null, and once you have entered the non-nullable-enabled area, you don't risk NullReferenceExceptions anymore, which will probably remove most bugs out there.
erikkallen
You can achieve this today if you use ReSharper. Check out the value analysis feature. I've been using this for a while and it achieves the same thing using attributes. Read here for more: http://www.jetbrains.com/resharper/features/code_analysis.html#Value_Analysis
Drew Noakes
@Andrew Russell, please see the remarks in the documentation for that class. NonNull is not intended for local use as you have done, it's intended to decorate non-nullable method parameters, and will ensure that those params are not null at any call site (achieved by the implicit coercion which performs the null check).
naasking
@naasking oh right (sorry, skipped the text wall). However, should I be able to do this: `string bar = null; Foo(bar.NonNull());`? As far as I can tell, in practice, this is just boils down to an unusual way to perform and document throwing an ArgumentNullException.
Andrew Russell
The problem with introducing non-null references is that null references are already too pervasive. In my opinion, the null reference is the single biggest design flaw in modern languages. You're allowed to return something different but not without changing the method signature! All references should be non-null by default, and you should have to explicitly say what methods return null. Or better yet, use an option/maybe type.
Matt Olenik
@Andrew, actually you don't have to call NonNull() at all if Foo() accepts a NonNull param, as the implicit conversion will do it for you. As for the advantages of NonNull, consider that if every reference param was wrapped in NonNull, your code is guaranteed free of null refs (unless you explicitly create them). Only code outside your control can introduce null refs, and these will happen only at the interface boundaries. I honestly don't know if this pattern will scale to large bodies of code, but the abstraction is a natural dual of nullable, so I included it in the library.
naasking
@naasking actually the implicit conversion is commented out in the linked code. Either way, the effect is the same... Overall your NonNull is interesting - but it has some disadvantages over the "normal" way (manual check/throw ANE with documentation) - 1) It's not normal; 2) The thrown exception doesn't say what function was called with a null argument; 3) It doesn't actually guarantee that you don't have a null (you could add a check to the Value getter - but even then you'd still need to manually check inside any function that needs an early out, ie: before performing any work).
Andrew Russell
@Andrew, sorry you're right, I temporarily disabled that and left in the implicit conversion back to T, since T->NonNull may throw, but NonNull->T never would, but I'm not 100% convinced I should leave it out. In any case, the intent is merely to automate null checking, since null checking is something many developers just automatically skip. Yes, the stack isn't quite as informative, but it should be informative enough. I'm afraid I don't follow your point 3.
naasking
@Matt Olenik: I agree with you 100% in theory. In practice, though, I realize that MS breaking all currently working code is neither likely nor desirable.
erikkallen
@naasking Say you have a client-exposed function that takes a NonNull parameter. There is no guarantee that it is actually non-null (see my first attempt at using NonNull!). The only place where the NonNull type could re-check for null, once inside your function, is when Value is accessed (in the property getter), as C# has no copy constructors. So if your function expects to be (ANE/NRE) exception-free (think: transactions/atomicity/etc), and does any work before accessing Value, you have a bug! The only fix is a manual null-check - back to where we started!
Andrew Russell
@Andrew, consider a source base that has few null checks. Now start to decorate any reference type method params with NonNull. On compile, it will break in a number of places due to the absence of an implicit coercion to NonNull. Now you simply add a .NonNull() call on each param expecting a NonNull, and your program is now null safe. The intent has always been to eventually supplement the abstraction with a static CIL analysis to prevent default struct types, which solves this problem and others too, but I have more important things to work on in Sasa at the moment.
naasking
+7  A: 

Exception grouping to avoid duplicating the same handling logic

try
{
}
catch (ArgumentOutOfRangeException)
catch (ArgumentNullException)
{
   // Catch a ArgumentOutOfRangeException or a ArgumentNullException
}

Multiple inheritance or a nice mixin implementation

public class A : B, C, ID
{
}

Switch done right without using break

switch (something)
{
    case 'A': ...
    case 'B': ...
}
Ion Todirel
-1: multiple inheritance is a royal pain to work with in a ton of conditions, and 99% of what it offers can be achieved through interfaces
RCIX
+1 for the mixin feature.
Charles Prakash Dasari
First I +1'd for exception grouping, then -1'd for multi inheritence, so I ended up leaving it alone. :p
Secret Agent Man
+1 for exception groups only
csharptest.net
I bet you would get more votes if you removed multiple inheritance. It was mentioned in another answer anyway.
ChaosPandion
-1 for removal of `break;`
Billy ONeal
Should make these multiple answers so we can vote separately.
Drew Noakes
+9  A: 

Rewrite FCL (Framework 2.0) so make all collections to be generic:

all this ControlCollection, XmlAttributeCollection, SqlErrorCollection

becomes Collection<Control>, Collection<XmlAttribute> and Collection<SqlError>

Of course you can use IEnumerable<T>.OfType<T> but it isn't so safe, is asspain and first of all - doesn't bring all benefits of generic usage from the sratch.

abatishchev
Don't forget `System.Collections.Specialized.StringCollection`.
Drew Noakes
+24  A: 

More syntactic sugar for automatically implemented properties; specifically, the ability to mark the compiler-generated field as readonly:

public int SomeValue { get; readonly set; }

SomeValue could only be assigned in the constructor, the setter would be implicitly private, and the C# compiler would need to generate a direct field access (behind the scenes) so that the CLR could tell that an initonly field was being used correctly.

Bradley Grainger
Man I would love to see this.
ChaosPandion
I've had this same thought several times--seems like an obvious and easy addition.
Dan
+1  A: 

I've been programming in C# for some time now. Before that I used Java and Linux. It hurts to admit it but in my opinion C# has become superior to Java. What I'd love to see is a CLR > 2.0 that runs on Linux. Making it open source would be cool too. I don't think Microsoft is making any profit with the language so the only problem would be the patents. But Sun has done it, so Microsoft could too.

Anonymous Coward
What's wrong with Mono?
Jesse McGrew
I haven't paid attention to the development of mono lately. You're right, it has become quite advanced.
Anonymous Coward
A: 

Imm keyword

This would work as "const" in C++, meaning the variable does not change in scope of "imm".

imm int x = 5;
x = 6; // error
macias
What's wrong with using `const` for this?
Gabe
const in C# is compile time only. Const in C++ has broader meaning.
macias
how about int! x = 5? I can also see the use over const because you would be able to set it to the value returned from a function. int! = foo(); Of course, they could extend the const keyword.
John
I don't care about the keyword name, I am just interested in mechanism. It could be "@@!$Type x" ;-)
macias
+4  A: 

Typedef keyword

The same as in C++. The reason: I am sick of typing List<Dictionary<string,Tuple<int,string>>> over and over again.

edit:

@Drew:

public class EnumArray<T> where T : struct
{
  typedef List<T> Container; // *, won't work in C#
  Container container;
  ...
}

(*) from this moment you could write everywhere in the class Container. This definition does not pollute outer space. And the benefits are obvious -- single point of control, not N. What's more you can define type as you need, quite contrary to C# which forces you to to declare alias in C/Pascal style -- at the beginning.

macias
You can declare a type alias with the `using` statement (inside your namespace declaration): `using MyList = System.Collections.Generic.List<MyType>`
hmemcpy
I know, but comparing to C++ typedef it is limited. For example in C++ it is usually used inside templace class.
macias
WOW! hmemcpy, thanks for that tip! I'd been dying for functionality like that, to avoid having to type over and over and over things like "KeyValueCollection(Of Integer, String)". I was curious if this worked also in VB with the Imports kw, tested it, and BAM! It does!! THANK YOU SO MUCH FOR THAT TIP!!! :)
eidylon
i'd rather have a strongly typed typedef
jk
@macias, I'm not that familiar with C++. Could you edit your question to show an example of what it would give you that you couldn't do with the using alias that @hmemcpy describes?
Drew Noakes
+17  A: 

Readonly automatic properties

So we could have something like:

public string Name { get; private readonly set; } 

or

public readonly string Name { get; private set; }

Like readonly fields, this property would be assignable only in the constructor and ideally also in object initializers such that this is still allowed:

var p = new Person { Name = "Edgar" };
// p.Name is now immutable
hmemcpy
this would make immutable programming much nicer
dan
+1. Have edited to include extension to this idea when using object initializers.
Drew Noakes
@Drew Noakes: Suppose the designer of the class intended the property to be readonly outside of the constructor. Your object initializer loophole would defeat that restriction -- since initializers are just series of set-property statements executed after the constructor is invoked.
Ben M
@Ben M, you're right. Still, that's an implementation detail not necessarily the way it ought to be. I'd like to see a readonly keyword on types too (public readonly class) that would enforce all fields to be readonly, and fields to also be readonly types. That way you could have a branch of object references completely frozen. The issue with the above is due to the timespan that the runtime allows modifying state. If that could be extended to allow object initialisers, it'd be nice. Something similar could be done with named constructor params.
Drew Noakes
WPF has a very low-level base class for most of the framework: `Freezable` that affords massive perf gains due to reduced memory copying and locking. That idea seems to me pretty general, and something that non-WPF code could benefit from. Maybe even something the compiler/runtime could support. BTW I have no suggestion on how to add these things from where we are today, but in a perfect world they'd be great.
Drew Noakes
+7  A: 

Compile-Time Aspects

The ability to use attributes to dynamically rewrite the AST at compile time, so we could create attributes such as the following which would be able to add common functionality to methods, classes, etc.:

public class MemoizeAttribute : AspectAttribute
{
    public override Ast RewriteMethod(Ast ast) { ... }
}

public class PublishExceptionsAttribute : AspectAttribute
{
    public override Ast RewriteMethod(Ast ast) { ... }
}

On larger projects there tends to be a lot of repetitive code for things like caching, publishing exceptions and so on which needs to be put into many methods. At the moment we're stuck with either putting the code into all methods (fail) or using third-party tools to do post-compilation IL rewriting (e.g. PostSharp) or runtime proxying and interception (e.g. Castle DynamicProxy).

Having compile-type aspects would allow this to be done in a type-safe way without having to rely on any third party tools, and allow the compiler to check the rewritten methods for correctness, and optimise them in the same way as source code.

This could form part of the compiler-as-a-service work that I believe the C# team are investigating.

Greg Beech
First class AOP would be amazing.
ChaosPandion
+3  A: 

Anonymous Iterators

For example, so you could write something like:

var cheeses = seq { "cheddar", "brie", "camembert", "wensleydale" };

And cheeses would be an IEnumerable<string>, with the compiler constructing an anonymous iterator to return the values on demand. At the moment if you need a sequence you have to either build an iterator method, or allocate an array with all the items in rather than having them returned lazily.

That said, I'm not sure how much value this feature would really add because iterator methods are trivial to build, and typically these sequences are fairly small so the overhead of array allocation would be minimal. But I guess it would be kind of a 'cool' mini-feature that probably wouldn't be hard to implement.

Greg Beech
One question -- what benefit would this have?
macias
It would avoid the need to write an iterator method or allocate an array for a simple sequence. As I said though, I'm not sure how much of a benefit this really is.
Greg Beech
But it's so easy to just write `new[]` instead of `seq`, I can't see the performance benefit being that great if at all.
Hightechrider
When the sequence is used, you have to allocate a new IEnumerator anyway, so the benefit is pretty questionable.
Jesse McGrew
Maybe this would be better if the yield syntax was augmented to support this: var cheeses = yield return { "cheddar", "brie", "camembert", wensleydale" };
Ted Elliott
+24  A: 

Remove C# attribute restrictions

Make attributes first class citizens by allowing any type of parameter type.

[SomeCoolAttribute(s=>s.Foo)]
public string MyProp { get; set; }
Jan Jongboom
This would be a cool idea... but it would require some pretty big changes to the CLR. You could just reference a type that would contain the method you want to execute for your Attribute.
Matthew Whited
I highly doubt whether this would change the CLR that much. The attribute is just some instance of a class, and the method is a constructor. It's just that generics and observables aren't allowed in this constructor. I believe there is an unofficial Mono build that supports this behavior.
Jan Jongboom
Attribute parameter data is serialized into the IL code. That's why you are limited to constant expressions.One thing that should be possible would be generic attributes. e.g. [Foo<Bar>] insted of the not compile-time checked [Foo(typeof(Bar))]
Robert Giesecke
I agree - I think attributes could be a *lot* more powerful.
Ben Aston
+1  A: 

Workflow designer controls?

So I can embed a workflow surface in a Windows / WPG application then add workflow components to the workflow surface that bind to parts of WF.

Obviously the actual workflow controls would be based on some base control that the developer would extend.

Would make for interesting process design.

Something like SQL Server Integration Services but within the context of any Visual Studio project I choose to embed it.

+3  A: 

C# -> JavaScript compilation. See http://projects.nikhilk.net/ScriptSharp.

Adrian
Would also be really good to get a Linq implementation for JS delivered with Visual Studio!
John
+5  A: 

Direct delegates to property getters

See here

You can create a delegate directly to a method:

Func<int> func = GetIntMethod;    // assuming 'int GetIntMethod() {}'

But to get a delegate to a property's getter you need to use another function:

Func<int> func = () => IntProperty;   // assuming `int IntProperty { get; }'

Would be nice to be able to use the property getter directly:

Func<int> func = get_IntProperty;
// or something like...
Func<int> func = &IntProperty;
thecoop
+2  A: 

It would be fantastic if MS offers some kind of proposals for future releases and will listen for community feedback a bit & not only top customers - something like what we have with PEPs and JSRs.

We already have open-source projects around community that are or will be core parts of the infrastructure.

... and a lot more. So if we can have some kind of organized open process for new features in C#/BCL with a bit of community review and feedback it would HUGE step forward for C#/.NET community.

PS. I understand that it's not about great things in code but abouth how great things appear in code.

Andrei Taptunov
MS does seem to be sourcing more from the dev community in recent years, but I agree that more could be done. On the other hand the JCP has spent a lot of time and energy debating how lambdas should be implemented in Java with nothing to show for it so far.
Drew Noakes
+1  A: 

Derive from T:

class Foo<T> : T where T : class

Constraint for interfaces:

class Foo<T> where T : interface

And of course both together, implementing interface T.

csharptest.net
+4  A: 

Ability to write F# alongside C# code.

CodeToGlory
Yeah, OO-stuff is a pain to write in F#. What I would love, is to write the "meta-level" (namespaces, classes) in C# and implement method bodies in F# ^^
SealedSun
+1  A: 

Property notification for use specially in AOP.

CodeToGlory
+73  A: 

Initial values for automatic properties

It would be very nice to be able to set initial values for automatic properties, something like this:

public string Name { get; set; } = "(NA)";

instead of having to create an explicit backing field:

private string _name = "(NA)";
public string Name
{
  get { return _name; }
  set { _name = value; }
}
yoyoyoyosef
I wouldn't mind having this but the syntax you chose seems a bit off.
ChaosPandion
VB.NET supports this.
Billy ONeal
I would rather have an attribute. Easier to implement too. Bit like the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx">`DefaultValueAttribute`</a>. But then fully automatic.
Jan Jongboom
maybe `public string Name { get; set; default "(NA)"; }` could be better
Victor Rodrigues
You don't have to create an explicit backing - just set it in the constructor...
BlueRaja - Danny Pflughoeft
@BlueRaja of course, but the code is so much easier to read and maintain when the initial assignment is right next to the declaration (especially when you have lots of properties and multiple constructors)
yoyoyoyosef
+3  A: 

The ability to inherit constructors from a base class. I realize this could most definitely be a breaking change if it was done unconditionally, so I would suggest an attribute you could apply to your class which would tell the compiler to inherit constructors for this class.

eidylon
+32  A: 

A short-circuiting null check operator, such that instead of having to write:

if (cake != null && cake.frosting != null && cake.frosting.berries != null) ...

You could use something like:

cake.?frosting.?berries.?loader

As proposed by Eric Lippert, to the Deep Null checking, is there a better way? question.

Dynami Le Savard
Many novice/incompetent programmers make this mistake. I upvoted, but wonder if it should be kept as is so that people have to learn why they get a null reference exception when they reference unchecked variables.
gmagana
They have this is Groovy as '?.' called the Safe-Navigation operator. I would love to have something along these lines.
Stephan
+3  A: 

Arithmetic operator overloading for generics

Jess
+28  A: 

"const" or "readonly" for local variables.

By which I mean, a way for me to declare a local variable in a method, calculate a value to put in it, and mark it as "cannot be changed any more".

This is something I really miss from C++, because it is so useful for "locking down" variables that you don't want to change. You know that you cannot change the value by accident later on in the method.

As in:

public void GetPixel(int x, int y)
{
    const int offset = x + (y * stride);
    ...
    pixelData[offset] = 0;
    ...
    offset = 5;     // Error: This variable is const. Saved me from making a mistake!
}

Even better, allow me to convert a variable into a const/readonly at any point:

public void GetPixel(int x, int y)
{
    int offset = x;
    offset += (y * stride);    // Can still change it, as it's a writable variable
    ...
    freeze offset;             // 'offset' is now enforced read-only by the compiler
    ...
    offset *= 2;               // Error: This is read only
}
Jason Williams
+1: Interesting... explicit immutable values. This could be interesting if this could lock all of the child values of that instance as well.
Matthew Whited
A nice way: freeze offset;
luiscubal
@luiscabal: Nice. Updated my answer to include this.
Jason Williams
There must be CLR support for this. It's very similar to VB.Net's Static keyword for local scoped variables
rossisdead
I'd prefer to reuse the const keyword, so to 'freeze' a variable for the rest of the code-block it should be "const offset;".Const should propogate to all children, too (unlike C where it doesn't protect things pointed-at)
Will
how about melt offset?
Behrooz
+13  A: 

yield enumerable

There is yield return for single elements, which is great until you need to return the elements of an IEnumerable, not the IEnumerable itself.

Current

public IEnumerable GetAllMembers(MyObject obj)
{
  yield return obj.head;

  foreach( object o in obj.BodyParts )
  {
    yield return o;
  }  

  yield return feet;
}

Proposed

public IEnumerable GetAllMembers(MyObject obj)
{
  yield return obj.head;
  // BodyParts is IEnumerable, and we want to 
  yield enumerable obj.BodyParts;
  yield return feet;
}
miko
I like it. F# already has this with "yield!". But how about reusing an existing keyword by calling it "yield from"?
Jesse McGrew
I'd prefer the syntax `yield foreach feet;` because it wouldn't introduce a new keyword and thereby break existing code.
SealedSun
yield foreach...I like that. It semantically fits with "yield return" and "yield break" .
miko
+12  A: 

Perhaps these are more like features for VS than C# or .net, but... fix references!

  • The ability to optionally put an "actual path" rather than just a "hint path" into an Assembly reference, so the compiler uses the exact file I specify and simply gives an error if it can't be found (instead of ignoring the dll that is actually sslap bang on the hint path and instead searching the dark side of the moon, finding something with a similar name, deciding "that's close enough", and silently corrupting my application with subtle fatal crash bugs that can stay hidden from testers for weeks).

  • Static linking of assemblies. i.e. ILMerge but built into the linker so you just tick "statically link" in the reference properties to have the referenced code bundled into your .exe/.dll.

  • The ability to change an assembly reference and have it ask if I want all references to that assembly in my Solution updated to the same one. Upgrading to a new verison of a 3rd party dll when you have 90 projects is no fun (even with a global search & replace on csproj files)

  • The ability to add a Project-reference to a Project that is not in the current Solution (i.e. refer to our libraries via their Projects rather than their output DLL files).

  • The abilty to reference a DEBUG build of our assembly in our DEBUG builds, and a RELEASE build of the assembly in our RELEASE builds. If you have any debug-only code, being forced to reference only one copy of the dll for all builds is really problematic. Microsoft assumes you will just put all your projects in a single Solution, but when you have hundreds of projects, you'll find that waiting 10 minutes for a build even if you only change a single line of code makes this approach a non-starter.

  • When an application runs and it fails to load an Assembly, it could report the name of the assembly it can't load in the exception instead of "The requested module can't be found". (ok, this may be lower level than .net, but, still. Arrrrgh!)

Jason Williams
+1  A: 

I would like to see support for SQL Server's Full Text Search in LINQ-to-Entities. i.e. Table-valued user defined functions should be supported in the designer... or an extension on .Contains() to support the FTS syntax.

LINQ-to-SQL has support for this; L2E v4 should too.

Boomerangertanger
+6  A: 

Initialization for automatic properties.

So instead of:

public MyType()
{
    Text = "Default Text";
}

public string Text { get; set; }

we could have

public string Text { get; set; } = "Default Text";

or

public string Text { get; set; default "Default Text"; }

or something to that effect.

David
A: 

There's a couple of issues that regulary messes up the readability and briefness of my code. These features are ideas for solving them, not very advanced features but would make for nicer code (IMHO)

IfNull and IfNotNull keywords

solves the "uglyness" of statements like

if (a != null && b != null) 

and the even worse

if (a != null && a.SomeProperty != null  && a.SomeProperty.SomeField != null).

instead you'd be able to write:

IfNotNull(a,b)

and

IfNotNull(a.SomeProperty.SomeField) 

where it handles the shortcircuiting of the last example.

conditional return statement "return?"

Allows you to do conditional returns more briefly in methods. so you can replace:

public void SomeMethod(object a)
{
  if (a != null)
  {
     //do stuff
  }
}

with

  public void SomeMethod(object a)
  {
    return?  (a == null)
    //dostuff
  }

return? (a == null) is shorthand for return? (a == null) : null. So if you needed to return an integer for instance you'd write return? (a == null) : 1

Fire keyword for events

Resolves the verbosity of code like this

private void FireApplicationTextUpdated(string applicationText)
{
    // copy ref to delegate for thread safety
    var evt = this.ApplicationTextUpdated;
    if (evt != null)
        evt(this, new EventArgs<string>(applicationText));
}

with

private void FireApplicationTextUpdated(string applicationText)
{
    Fire(this.ApplicationTextUpdated(this, new EventArgs<string>(applicationText));
}

The Fire keyword triggers an event only if the event has subscribers

As I said, there are different solutions/hacks to many of these issues but most of them means compromising either performance, verbosity or breaking default code formatting rules so I think they'd be nice additions

MattiasK
if ( a == null ) return; seems way better IMO.
kenny
VB.NET has the "Fire" keyword - essentially. RaiseEvent EventName[(<arguments>)]. Would think the C# team should be able to implement this fairly easily.
eidylon
yah, and it would address all these questions and issues on how to be raise events thread safely without risking racing conditions etc. Seems like a no-brainer
MattiasK
A: 

A keyword on a superclass method that ensures all children call the parent:

class prnt{
public virtual mustbecalledbychild string prntMethod(int arg1, double arg2){ //code}
}

//Would cause compiler warning:
class child:parent{
public override prntMethod(int arg1, double arg2){
return "Hello World";
}
}

//Would not cause warning:
class child:parent{
public override prntMethod(int arg1, double arg2){
string prntstr = base.prtnMethod(arg1,arg2)
return prntstr + "Hello World";
}
}

You could have variations that look for whether the parent method is called with the same arguments supplied to the child.

Carlos
Hopefully this isn't something you want to do often; and for when you do, you can use a slightly different pattern. Make the method which 'must be called' sealed, and offer a new virtual protected method or two, which is called by the sealed method and by default does nothing but which subclasses can override.
Wesley Hill
Agreed, that's a much better pattern. I'm thinking of documentation that explicitly says "if you call this, you must call parent." If I run into an external lib with this type of explanation, I want the compiler to remind me.
Carlos
I agree with @wesleyhill. You can already achieve this using the pattern he describes. There are examples of this in the .NET framework (eg. WPF's Arrange and ArrangeOverride methods).
Drew Noakes
A: 

Braced switch syntax- (I like braces)

switch 
{
   if(c<0) printf("Less than 0");
   if(c>0)
   {
      printf("Greater than 0");
      printf("The value is: %d",c);
   }
   printf("Equal to 0");
}

The idea is, only one statement (or block with brace) is allowed to execute. The last statement without any conditions is the default statement. Used printf because I want to have it in all C-like languages.

Gulshan
You can do this already. Use case then add braces.
RCIX
@RCIX you can't put conditionals in case statements (such as `c<0`).
Drew Noakes
How is it different from `if / else if / else` ?
Thomas Levesque
@Thomas Just replacement of lot of "else" with one "switch" and braces defining a separate block. It's more like a brace-based replacement of switch-case block rather than replacement of "if / else if / else". And you can perform switch-case operations with "if / else if / else" anyway (with some exception).
Gulshan
+8  A: 

An extension to automatic properties so that when you need to do something extra you don't have to actually create a private variable (which is annoying). This could be achieved with new "auto" and "backingfield" context-sensitive keyword like so:

/// <summary>
/// Gets or sets the character's level. The level must be an integer between 0 and 100, inclusive.
/// </summary>
public auto int Level
{
    get { return backingfield; }
    set { backingfield = MathHelper.Clamp(value, 0, 100); }
}

Could even extend it so you can even leave one of the properties automatic, like:

/// <summary>
/// Gets or sets the character's level. The level must be an integer between 0 and 100, inclusive.
/// </summary>
public auto int Level
{
    get;
    set { backingfield = MathHelper.Clamp(value, 0, 100); }
}

By default get; would be the same as get { return backingfield; } and set; would be the same as set { backingfield = value; }

It could also issue a warning (or error) if you do this:

 /// <summary>
/// Gets or sets the character's level. The level must be an integer between 0 and 100, inclusive.
/// </summary>
public auto int Level
{
    get;
    set;
}

Since it's the same as the current automatic property implementation, you don't need the auto keyword. auto simply activates the backingfield keyword-variable.

Jake Petroules
Perhaps something like underscore would work in place of backing field. set { _ = Mathhelper.Clamp(value,0,100); }
kenny
I think that might decrease readability somewhat, though, plus Microsoft has some style rules for variables not to start with an underscore. Perhaps it could be shortened to just "field"?
Jake Petroules
Hmmm... although this is a good idea, I think I'd rather see every property *automatically* receive a backing field without requiring an extra keyword at the property level. This backing field would be automatically compiled out if it's never referenced by a getter or setter that's defined, automatically used as a getter or setter if there is no block specified for a getter or setter. Referencing it is still debatable, I don't like "field" or "underscore" or "backingfield"... "value" is out.... what about "property"?
Randolpho
Hmm... or better yet, remove any possibility of recursion on a property getter and just refer to the backing field by the name of the property?
Randolpho
@Randolpho Interesting ideas, I like. I wonder if using the name of the property as the backing field would generate any sort of conflicts? That's certainly interesting how it eliminates the possibility of recursion. Although, what if you did: `MyField = MyField;`?
Jake Petroules
@JAke Petroules: I'd say compiler error there.
Randolpho
+1  A: 

I know this is not a language/syntax future, but I want to see C#/.NET really multi-platform. I know some of you can mention Mono, but ...

Incognito
Yes it is very important.
+9  A: 

Same as for C# 4.0.

Missing:

  • methodof/propertyof
  • delegate and enum generic constraints
  • lambda-expressions as attribute parameters
  • generic attributes
  • &&=, ||=, ??= assignments
  • way to specify generic constraints on operators
  • yield foreach

Nice to have:

  • AddRange support in read-only collection initializers
  • TThis pseudo-type in generic constraints (or even full JavaGI)
  • Some way of null-proof property traversal, like ?(a.B.C) returns null if a is null.
  • Shortcut syntax for IEnumerable
  • Object initializer support for factory method return values
  • Better forms of string.Format -- $"All ${userName} bases are belong to us".
  • Additional LINQ operators for Take/Skip, Single and ToList/ToArray
  • Access to current item index in LINQ expression
  • Immutable types
  • Initialization for automatic properties
Andrey Shchekin
Regarding `methodof`, see [this article](http://blogs.msdn.com/b/ericlippert/archive/2009/05/21/in-foof-we-trust-a-dialogue.aspx). Could you elaborate on "yield foreach" ?
Thomas Levesque
BTW, many of your suggestions have already been posted and have many votes... no need to repeat them here. Also, please put your suggestions in separate answers, so we can vote for them separately
Thomas Levesque
You are right, I should have split them. I'll the ones that do not yet exist as a separate suggestions.
Andrey Shchekin
See https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=256934 for yield foreach.
Andrey Shchekin
A: 

In NETCF, for Smart Devices, the ability for a UserControl to inherit from a class which inherits from UserControl, allowing you to create your own UserControl base classes for shared functionality. Right now if you try to do this, it throws an error that UserControls MUST be inherited directly from System.Windows.Forms.UserControl.

eidylon
+2  A: 

When compiler doesn't need parenthesis or ';', avoid these constraints. The code becomes more fluent, this is good for a DSL-ysh code also.

Example:

if (foo) => if foo

DoIt(); => DoIt

DoIt(param1, param2); => DoIt param1, param2

Reverse if declaration

This syntatic sugar is implemented in some languages, I find it really interesting concerning readability

Instead of

if(foo) DoIt();

just

DoIt if foo

also this

DoIt unless foo
Victor Rodrigues
So switch to VB.NET already...
gmagana
VB.NET, dsl-ish? No way.
Victor Rodrigues
I like some of these, though the lack of semicolons is not a good idea.
RCIX
...or maybe IronRuby?
Drew Noakes
The redundancy of `();` improves the compilers ability to recover from errors. If a semicolon is **always** guaranteed to be at the end of a statement, in case of an error the compiler can just skip to the next semicolon and continue from there.I find the reverse conditions very hard to read. Don't like it.
SealedSun
+26  A: 

String Interpolation

These two lines of code...

var a = String.Format("There are {0} elements", list.Count);
var greeting = String.Format("Hello {0} how are you?", name);

Would be a lot nicer like this...

var a = $"There are {list.Count} elements";
var greeting = $"Hello {name} how are you?";

Per Miguel de Icaza's implementation which can be found at http://tirania.org/blog/archive/2009/Dec-20.html

randolphcabral
Great suggestion, as long as it would be checked at compile time.
gmagana
@gmagana Agreed, compile time check else useless.
randolphcabral
+1. As an aside, DebuggerDisplayAttribute has a similar capability, and can even call methods from within the string. Note that the string is not checked at compile time for this attribute, however.
Drew Noakes
I was going to say I didn't like this idea but with Drew bringing up DebuggerDisplay I have to say that feature is really awesome to support that natively with strings seems alot more logical now.
Chris Marisic
I find myself constantly hating having to type String.Format type code. I would love this. +1
Chris T
I actually wrote a class that does something similar : `string text = StringTemplate.Format("Hello {name}, today is {date:D}", new { name = "John", date = DateTime.Today });`. I hate to use numbers for things which have names...
Thomas Levesque
A: 

Automatic cast after 'is'

instead of:

if(someObject is SomeLongAndAnnoyingClassName)
    ((SomeLongAndAnnoyingClassName)someObject).Name = "New name";

it becomes:

if(someObject is SomeLongAndAnnoyingClassName)
    someObject.Name = "New name";

and the compiler would emit code something like:

if(someObject is SomeLongAndAnnoyingClassName)
{
    var someObjectTemp = (SomeLongAndAnnoyingClassName)someObject; //see? var is useful!
    someObjectTemp.Name = "New Name";
}
Oggy
Have a look at the `as` operator. Also, your suggested would break 1) existing code, 2) core assumptions about the syntax of C#, and not in a good way. Basically, the name `someObject` would have different *static* meanings depending on the *runtime*. No, not good.
Konrad Rudolph
I like it. Maybe not necessarily this syntax, but it would be nice to have *some* kind of sugar to cover up the pattern "Foo xAsFoo = x as Foo; if (xAsFoo != null) { do something with xAsFoo; }"
Jesse McGrew
@Konrad Rudolph: Not necessarily. It's like the `value` implicit variable in set accessors for properties. It needs a little more work than that though, to make it clear that someObject becomes SomeLongAndAnnoyingClassName only within the scope of that if. I'll edit and provide an example of what i think he wants.
RCIX
It might be a little more verbose than what you're suggesting, but the `as` operator basically does what you want. The compiler maps `is` to one IL instruction, and `as` to another. If I understand what you're saying, you'd want the compiler to be clever enough to know when you actually meant `as`. Also, doing an `is` and then a cast would be unnecessarily slow (which is why the `as` operator was created). The compiler would be best off emitting `var temp = someObject as MyType; if (someObject!=null) { someObject.Name = "New Name"; }`
Drew Noakes
A: 

Absolutely nothing.

The platform needs a period of stability and creeping featurism has already added unnecessary things to C#. (var - I'm looking at you.)

JonB
No platform is EVER complete, plus there are uses for var (just like goto)....
RCIX
Goto has been around since the dawn of time, so a poor example.I'm not saying there aren't uses either, just that there are other ways and the other ways are better.Adding features for the benefit of fringe cases is a mistake (IMO, of course).The drift away from strong typing will bite you.
JonB
Use the small subset of features, who is forcing you to use them all? Omit "var" and simply typeDictionary<List<Tuple<string,int,Hashtable<int>>>,string> x = new Dictionary<List<Tuple<string,int,Hashtable<int>>>,string>(); all the time.
macias
@JonB, what is wrong with var? Why do you need to write the type definition anyway? Look at languages like F# -- you'll hardly see a type declaration anywhere, yet it's totally typesafe. I wasn't sure about var at first, but I actually find it quite useful in many cases now, especially when the type name is on the RHS of the assignment.
Drew Noakes
var is great, it's not like variant from VB! Although I do agree with you that stability of the core framework needs some prioritization with more releases of independent projects like the way MVC was built independently from the .NET release cycle.
Chris Marisic
I was about to vote +1 but then I read your statement about var. I agree that stuff like LINQ syntax (not the extensions, those are cool. They really save a lot of time) or dynamic doesn't really belong into C# if you ask me. But `var`? It's still typesafe (unlike `dynamic`) ^^
SealedSun
@macias, When you see that, you want a syntactic flourish rather than a type declaration?@Noakes, It conceals type information without really needing to be there. In the second part, how are you using a type that you don't know how to express?@Marisic, Yes, I fear my bracketed aside about var has distracted from the main point.@SealedSun, Thanks for reminding me of dynamic, that's another one.
JonB
@macias:whats the use of that type?just a related but not complete example is enough for satisfying me.
Behrooz
@Behrooz, this one above -- I made that up, but I often deal with complex types, even dictionary of lists, or list of lists is enough for me to get tired of writing. And using "var" is useful also when you change types, for example from List to LinkedList.
macias
@macias:my job is dealing with arrays, lists, linked lists, trees, ... but this one was new to me(using a Tuple with a HashTable<int> as key).
Behrooz
+1  A: 

Inline assembly language.

abmv
What assembly language? CIL? x86? x86_64?
SealedSun
IL, I guess... but I don't see many cases where it would actually be useful
Thomas Levesque
x86_64 would be cool too, we will beat C++ guys.
Behrooz
+4  A: 

How about making it a compiler error when a get property returns itself, causing a StackOverflowException?

Something that would prevent:

public int Amount
{
    get { return Amount; }
}
hmemcpy
I think an error is too much, given maybe someone would like to make some recursion. But a warning, yes, this is something feasible to do.
Victor Rodrigues
How about an error when there is no possibility for the loop to exit?
Sekhat
If you're going to warn about infinite recursion for properties getters, why not do it for all methods, including property setters? I'm pretty sure ReSharper will already do this for you.
Drew Noakes
Um, don't you have to solve the halting problem to show all infinite recursions?
helium
@helium: You can detect/mechanically prove certain patterns of infinite recursions. The halting problem states that it is impossible to predict termination **in general**.
SealedSun
+10  A: 

Full support for Linux Platform. Mono is not happening.

nitroxn
...and by extension, Mac support. MS has obviously ported a large degree of the CLR and framework (threading, GC, networking/IO, security, graphics) to Linux and OSX for Silverlight.
Drew Noakes
@nitroxn agree about Linux support. At least we are three to mention that.
@Drew What you mean MS ported... AFAIK it is Novel who works on Mono.
@MigNix, there is a MacOS version of Silverlight made by Microsoft (I'm not sure about Linux)
Thomas Levesque
@Thomas Yes for silverlight it is clear. I was asking about CLR as mentioned by Drew Noakes.
@MigNix / @Thomas. It appears that MS has been working with Novel on Silverlight for Linux. http://weblogs.asp.net/scottgu/archive/2007/09/04/silverlight-1-0-released-and-silverlight-for-linux-announced.aspx. To quote: ... today we are announcing a formal partnership with Novell to provide a great Silverlight implementation for Linux. Microsoft will be delivering Silverlight Media Codecs for Linux, and Novell will be building a 100% compatible Silverlight runtime implementation called "Moonlight".Moonlight will run on all Linux distributions, and support FireFox, Konqueror, and Opera.
Drew Noakes
A: 

Microsoft gave us the membership provider in .net 2.0 and saved countless developer hours that all would have been spent on the same thing most being buggy and error prone inferior solutions.

I'd like to see more features like this, the 2 that come to mind are an e-commerce system that only requires simple account configuration and can handle ssl transactions over my domain and not redirect to a pay service. I don't want to have to write the same code time and time again to deal with gateway payment processors.

The second item I'd like to see is internal site messaging that will scale over time. This seems like a logical extension the membership provider. I'd like users on a site to be able to send messages to other users on that site and I'd like message inbox management provided as well. Website based instant messaging capabilities would be nice too.

Both of these features are requirements on a large majority of all sites, why should we as developers have to keep implementing the same code over and over?

MegaCraig
+8  A: 

Interfaces / abstract classes for all .NET library concrete classes

Yes, I know this is rather difficult to provide, but unit testing classes in .NET can become something much more harder because of some dependencies. If my class uses SmtpClient, I can't test it by mocking the dependency (just an example, there are tons of other classes in the same situation). They've made it the right way in some assemblies, but did it without any abstraction in others. Using dependency injection, unit testing and extending behavior could suck less if we have this.

Chained Comparisons

bool isBetween = (a > 20) && (a < 30);

if we could do this, it would be nice:

bool isBetween = 20 < a < 30;
Victor Rodrigues
I agree with this, to an extent. I agree wholeheartedly that interfaces help with unit testing, but interfaces should only be required where the class deals with some external dependency that we may want to mock. I don't need to mock, for example, an integer. I therefore don't need an IInt32. Although INumber, as suggested elsewhere, might not be bad. Your example, however, definitely deserves an interface.
Randolpho
That said, there are techniques you can use to make unit testing `SmtpClient` go better. You could build an `EmailSender` class, for example, with virtual methods (or an interface) that wraps all use of `SmtpClient`. Bind against it rather than SmtpClient and you've got an easy test double.
Randolpho
Yes, Randolpho, 'all .NET concrete classes' was not really my goal, since things like int has no need to mock. Today I do this way, wrap the access to these classes.
Victor Rodrigues
This should be two separate answers. +1 for chained comparison operators.
Drew Noakes
1) wouldn't that be 20 < a < 30 ? 2) extend to 20 < a < 30 < b < 40 and a == b == c
devio
+1 for increased testability when using some of the built .NET library classes. I honestly can't even remember how many wrappers I have for .NET objects just so I can test my code.
Adam
@devio you're right! I've corrected the post, thanks.
Victor Rodrigues
+1  A: 

Support for XSLT2. Also, an XProc processor would be awsome!

+4  A: 

Indexed properties, like in VB and COM :

    public class Foo
    {
        private string[] _values = new string[3];
        public string Values[int index]
        {
            get { return _values[index]; }
            set { _values[index] = value; }
        }
    }

    ...
    foo.Values[0] = "hello";
Thomas Levesque
Er, `public string[] Values { get; private set; }` does the same thing.
BlueRaja - Danny Pflughoeft
Well, in that case, yes... But in a real-world scenario, I could make the setter private, or put some kind of validation in it, or implement lazy initialization in the getter...
Thomas Levesque
+25  A: 

Language support for property change notification (INotifyPropertyChanged) :

public observable int Foo { get; set; }

(this was suggested on uservoice for WPF bindings, but it would be useful in other areas too)

Thomas Levesque
Big +1 for observable baked into .NET!
Chris Marisic
`INotifyPropertyChanged` is used with bindings, and bindings use property name as string of course, but one could have their own need to observe properties. In that situation I don't like that I get property name as string, because if I change the property name, code with that string will be not refactored (obviously). Would be great having something different than string in `PropertyChangedEventArgs`, but I don't know what could it be. `typeof(MyClass.Foo)`? ;)
prostynick
@prostynick, there is a way to trigger the PropertyChanged event without passing the property name as a string, using Linq expressions. Google "static reflection" for some examples
Thomas Levesque
@Thomas Levesque, Thank you. Anyway `observable` could be great.
prostynick
+7  A: 

Allow T? for reference types

Currently it's not possible to write generic code using null values that works with both value and reference types. "T?" is only allowed when T is constrained to be a value type.

I propose that "T?" be allowed even when T is unconstrained. Since reference types are always nullable, "T?" should be the same as "T" when T is a reference type, or "Nullable<T>" when T is a value type. The "Value" and "HasValue" members should be forbidden on an unconstrained "T?", requiring explicit null checks and casts instead.

(Alternatively, the Nullable class could just be extended to work with reference types, in which case "T?" would always mean "Nullable<T>".)

Jesse McGrew
+1  A: 

I would like to see the next version of C# (not the CLR!) allow me to return an "anonymous" type from a method. Often times I have to create a class specifically for this purpose. I feel it is a natural progression for the C# compiler to go ahead and generate the class for me. Currently, the implementation of anonymous types is handled in the clr. This would promote an anonymous type to a generated type. It would also maintain full static type safety and allow easy interop with other languages. The only real way to do this currently is to return dynamic and lose static type checking and intellisense.

John
Ah, but what syntax do you propose? something like `public anonymous Bar() {return new {Foo = 123,}}`?
RCIX
Yup, something like that would work fine for me. Or to be more accurate we could use generated or concrete or even... T.
John
@RCIX @John, what about reusing the `var` keyword? `public var Bar() { ... }`. I read a commend somewhere by Eric Lippert saying something along the lines of _"unfortunately C# doesn't have implicit return types from methods". I can't find the reference to his comment though, unfortunately.
Drew Noakes
I'd be ok with that. The only real catch is that the compiler would need to compile it with a real name so that other languages and libraries can work with it. I suspect this is where most who are against it object. However I'd even be ok with forcing it to internal scope to minimize use outside the library it is in.
John
A: 

The ability to simplify LINQ queries when i want to order a collection or something -- i actually like using the syntax and it's a bit of a pain to have to write an entire select statement.

Current:

List<Foo> foos = new List<Foo>();
foos = from foo in foos orderby foo.Bar descending select foo;

Proposed:

List<Foo> foos = new List<Foo>();
foos orderby obj.Bar descending; //obj is a context-sensitive variable
//which translates into...
foos.OrderByDescending(obj => obj.Bar);
RCIX
`OrderByDescending` doesn't do a sort-in-place. It returns an `IOrderedEnumerable`. You'd need to do some kind of assignment. Your last lines might therefore read: `foos = (foos orderby obj.Bar descending).ToList();` and `foos = foos.OrderByDescending(obj => obj.Bar).ToList()` respectively.
Drew Noakes
Good point, and i didn't think of that, though my understanding was that it does the sorting when you actually go to use it. There is a difference, but sometimes you don't care as much about it.
RCIX
+4  A: 

Something like this

public enum Animals {
    Dog { 
            public override void Attack() {
                Console.WriteLine("Grrr...");
            }
    }, 
    Cat { 
            public override void Attack() {
                Console.WriteLine("Meeow!");
            }
    };

    public abstract void Attack();
}

public void Main(Animals animal) {
    animal.Attack();
}

or

public void Main(string animalName) {
    Animals animal;

    if(Enum.TryParse(animalName, out animal)) {
        animal.Attack();
    }
}

or maybe

public void Main(string animalName) {
    Animals.ValueOf(animalName).Attack();
}

Just like java

Kim Tranjan
A similar suggestion has already been posted [here](http://stackoverflow.com/questions/2875533/what-features-do-you-want-to-see-in-net-5-c-5/2876193#2876193). However I like the idea of overriding methods for each enum value...
Thomas Levesque
oh sorry i didn't see+1 for your suggestion! thanks
Kim Tranjan
+4  A: 

Delegates have to be checked for null before they can be called. I would like a variant on the syntax such as;

DelegateType? DelegateVar;

Such a delegate could be invoked even if when its value is null, in which case it would return the default of the return type the function. All done in a thread safe way.

Peter J Fraser
A: 

Allow in indexer of a foreach to be a ref

foreach( ref var a in AnArray ) { ... } foreach( ref var s in AnEnumerableofStruct ) { .... }

because the index is a ref, a = SomeValue would work in the case of an array, and s.X = SomeValue would would work in the case of a struct.

About the only time I now use for(;;) is to manipulate arrays, this would remove the need in most cases

Peter J Fraser
Given foreach works over IEnumerable which is a purely read-only interface, how do you anticipate this would work? Special handling just for arrays or ILists?
Drew Noakes
+1  A: 

A method to mark a variable from an outerscope that is in the body of a lamda function to be evaluated at the definition of the lamda funcion, rather than the default of creating a reference to the variable. This would save created dummy local variables when using such lamda functions in a loop.

A new syntax would be required.

Peter J Fraser
+3  A: 

Interface operators or extension operators

... or anything which would let you define operators for an interface. An example of an extension operator:

interface INumericArray
{
    INumericArray MultiplyBy(INumericArray b);
}

class NumericArrayExtensions
{
    public static INumericArray operator *(this INumericArray a, INumericArray b)
    {
        return a.MultiplyBy(b);
    }
}

There would be a need to allow the this to be applied to the second argument though to support something like INumericArray twiceMyArray = 2 * myNumericArray;

Among other things, this feature could be used to help add the array-based programming paradigm to C#'s multiparadigm capabilities:

Wesley Hill
Why don't you edit this into two separate answers? People could vote for them individually.
Drew Noakes
I agree with Drew... I'd vote for the first suggestion, but not for the second. BTW, I'd like to suggest a small change to your `INumeric` interface. I would declare it as follows : `interface INumeric<T> where T : INumeric<T>`, and `Multiply` would return a `T` (so that you can keep the strong typing)
Thomas Levesque
Thanks for the comments; I removed the Slice literal so my answer only has one feature for voting. Thomas, I made a fix to the interface to try make my intention clearer.
Wesley Hill
+4  A: 

Static inner methods.

public int SomeMethod(int input) {
    private static int double(int a) {
       return a * 2;
    }
    return double(double(input));
}

Just to keep the scope of the inner method to only the outer one, I don't care if the compiler just changes it to.

public int SomeMethod(int input) {
    return double_xyz(double_xyz(input));
}

private static  int double_xyz(int x) {
    return x * 2;
}

But I'd like to keep it out of the namespace of the whole class without having to use Func<>s.

Toby
What does this give you that you can't already do with closures (apart from a different syntax?).
Drew Noakes
I like it. It lets you make very readable code without having tons of small static methods in a class that have no relation but to 1 method in the class.
Chris Marisic
I don't see why you can't just do this as var d = (int a) => a *2; return d(d(a));
Stephan
Well for more complex functions I'd like to use the compiler to ensure that the function is *not* capturing local variables. Also to avoid variable name scope collisions ie: "A local variable named 'x' cannot be declared in this scope because it would give a different meaning to 'x', which is already used in a 'parent or current' scope to denote something else"
Toby
A: 

Possibility to declare local variables anywhere, e.g.

mydict.TryGetValue(key, out var value)

if ((var x = expression) != 0)

Some way to avoid code duplication in exceptions handlers

try {
    ...
}
catch (SomeException err) {
     // do something
}
catch (SomeOtherException err) {
     // do something else
}
catch continue {
     // do something common for all catched exceptions
}
finally {
     // always do something
}
adrianm
The first suggestion doesn't really make sense because then you have no scope. What is the point of creating the variable when it is almost immediately out of scope. I really like the second suggestion though.
Stephan
A: 

I would love to see that this is possible:

public static void Repeat(int x)AndAfterWrite(string s)
{
}

Which can be called either with Repeat(5)AndAfterWrite("Jos") or Repeat(5).

This way we get some readable code again without having to create a fluent API.

Tim Mahy
For some reason looking at this just screams Yuck! in the back of my head.
Chris Marisic
I feel like returning an instance of the class is better and more readable than this. Can you just return the "Type" for the class you want so you can do the same thing with static methods?
Chris T
readable ?? That's not readable to *me*... I can't even understand what it means !
Thomas Levesque
+2  A: 

Virtual constructors and virtual static methods like in Delphi.

LionSoft
+2  A: 

Support for Mixin's.

Tim Mahy
+1  A: 

Roles

Update: I've created a post about this idea.

I'd like to see traits in .NET (pdf), but, unlike in the traits paper (pdf), extended with state as well.

This is what Perl 6 and Moose call roles.

Unlike in Scala, roles would need explicit conflict resolution.

They're compositional, so it's NOT multiple inheritance.

For example:

role RSwitchable {
  public void TurnOn() {
    _on = true;
  }
  public void TurnOff() {
    _on = false;
  }
  public bool IsOn {
    get { return _on; }
  }
  public bool IsOff {
    get { return !_on; }
  }
  bool _on = false;
}

role RDimmable { // I can't find a better name ...
  public RDimmable() {
    Intensity = Min;
  }
  public int Intensity { get; private set; }
  public void Increase(int steps = 1) {
    Intensity = Math.Min(Max, Intensity + steps * Step);
  }
  public void Decrease(int steps = 1) {
    Intensity = Math.Max(Min, Intensity - steps * Step);
  }
  protected int Max { get { return 100; } }
  protected int Min { get { return 10; } }
  protected int Step { get { return 10; } }
}

class Fan : RSwitchable, RDimmable { 
  protected supercede int Max { get { return 200; } } // supercede is akin to override
}
class Light : RSwitchable { }
class DimmableLight : Light, RDimmable { }

// ...

var livingRoomLight = new Light();
livingRoomLight.TurnOn();

var bedRoomLight = new DimmableLight();
bedRoomLight.TurnOn();
bedRoomLight.Increase(steps: 5);

// ...

public void TurnItAllOff(IEnumerable<RSwitchable> appliances) {
  foreach (var a in appliances) {
    a.TurnOff();
  }
}

Roles encapsulate separate concerns, and provide reusability beyond anything possible with C# today.

Jordão
A: 

An exception-coalescing operator:

Instead of something like

int value;
aFunction(int.TryParse(valueString, out value) ? value : 0);

Something like:

aFunction(int.Parse(valueString) ??? 0);

This would be very useful for proving defaults in situations such as:

IDictionary<string, string> mydict = getAStringDictionary();
Console.WriteLine(mydict["SampleElem"] ??? null);

For reference, value = a ??? b; is the same as:

try {
    value = a;
} catch {
    value = b;
}
MiffTheFox
-1 : using exceptions for flow control is a bad practice and harms performance. Also, that would catch *any* exception, when it should only catch `FormatException` (in that case). Last issue : you would have no way of knowing that an exception occurred, which, in the end, is the same as swallowing an exception with an empty catch block
Thomas Levesque
+1  A: 

I would like to see a way to:

  1. Specify "friend" class on the setter. This would come in handy for example when synchronizing bi-directional relationships so that one does not have to expose a setter on the child as protected internal or public just to be able to set it. It would be visible in intellisense only in the context of the "friend" class.

  2. Specify ReadOnly collections, that would prevent not only changes to the collection but also to all objects in the graph, so that one could not do something like this:
    Parent.Children.ElementAt(0).SomeOtherProperty = somevalue;

  3. Return a instance from the getter as immutable so that could no do something like this Parent.Child.Parent = someOtherParent.

Example:

public class Parent
{
   private IList<Child> _children;
   public IEnumerable<Child> Children
   get
   { 
       return _children.AsReadOnly(); // one could not modify items in the list or any of their properties. 
   }

   public Add(Child child)
   {
      _children.Add(child)

     // this would be only available in the context of the "friend" class type, in our case       
     //Parent. Nowhere else could one set Parent
     child.Parent = this;  
  }

}

public class Child
{
     public Parent Parent
     {
        get 
        { 
          // this would return it as Immutable object that could not be further changed
          return _parent.AsImmutable();  
         }

         [SettableBy(typeOf(Parent)]  // this specifies the "friend" class
         private set 
         { 
            _parent = value;
          } 
      }
  }
epitka
+2  A: 

Ability to invoke static method on the generic parameter

public T Create<T>() where T : static Create()
{
     return T.Create();
}
epitka
currently, generic instances of reference types are all handled by the same jitted code (the instance for type System.Object). With static methods, you'd have to jit a separate copy for each an every instance in your program.
SealedSun
I think i wished this more than 1000 times just a few days ago.
Behrooz
+4  A: 

A nameof function, similar to typeof but returns a string with the name of a type or member.

class Program {

   static void Main() {

      Console.WriteLine(nameof(Program));
      Console.WriteLine(nameof(System.String));
      Console.WriteLine(nameof(string.Empty));
      Console.WriteLine(nameof(Main));
   }
}

output:

Program
String
Empty
Main

A lot of people are using lambda expressions for the same purpose because they are type-safe, the downside is that lambdas are evaluated at runtime. nameof can be type-safe and replaced by strings by the compiler.

eg.

NorthwindContainer container = new NorthwindContainer();

var productsWithCategory = container.Products.Include(nameof(Product.Category));
Max Toro
+1, I'd love it ! This looks similar to the [hypothetical `infoof` operator](http://blogs.msdn.com/b/ericlippert/archive/2009/05/21/in-foof-we-trust-a-dialogue.aspx), but it wouldn't have the same issues (overload resolution etc.) since we just want the name...
Thomas Levesque
+1  A: 

Not very useful in the end, but I like the Perl unless condition and syntax like

print "hello" If x = 0
David Brunelle
A: 

Numeric literal suffixes for all numeric types

Currently the following suffixes exist :

  • 1 (no suffix) : int or double (based on decimal separator)
  • 1U : uint
  • 1L : long
  • 1UL : ulong
  • 1f : float
  • 1d : double
  • 1m : decimal

For other numeric types, you have to cast explicitly :

  • (byte)1
  • (sbyte)1
  • (short)1
  • (ushort)1

I'd like to have the following suffixes added :

  • 1B : byte
  • 1SB : sbyte
  • 1S : short
  • 1US : ushort

And since there is a BigInteger type in 4.0, it would be nice to have a suffix for it too (perhaps use lowercase b for byte, and uppercase B for BigInteger)

Thomas Levesque
or BI for big integer
Chris T
+2  A: 

The ability to access extension methods from the class they're assigned to without having to use this.

This is kind of a niche feature, but it happens to me a lot in WPF. I have a few extension methods assigned to UIElement/FrameworkElement and I use them from classes that derive from Window or UserControl. So, if I have:

public static void Extension(this UIElement e)
{
}

Which does nothing, but illustrates the point. And I have a:

public class DemoWindow : Window
{
     public void DemoMethod()
     {
         Extension();
     }
}

This is illegal. I have to instead call this.Extension(); which while trivial to do is rather confusing and seems like something that would be easy to change. It'd also help in eliminating those Util classes that plague any large project.

If nothing else, Visual Studio offering to correct the above into the this.Extension() call would be nice.

JustABill
A: 

Structural constraints

Structural constraints, including constructors and operators as mentioned in other answers. Not only for generic constraints but usable everywhere in the language like any other type. This differs from interfaces because you can't add an interface to a type you didn't write, and more than often I found myself thinking "If only those classes implemented a common interface for method X".

skeleton MyConstraints {
  void MyMethod(string a);
  operator ==(string s);
  new(int i);
};

Then I could use:

class MyClass<T> where T : MyConstraints {
  // and be able to use MyMethod, == or construct a new T(int) here
}

Or simple declare a variable of type MyConstraints:

MyConstraints c = ... ;// any object implementing MyMethod, == and a constructor taking an int here

And be able to pass it around functions like any type. You could also assign an anonymous type to an existing constraint since it's not different from any other class.

Julien Lebosquain
+1  A: 

Higher Order Generics (Generic Parameters with Generic Parameters)

I would like to be able to constrain generic parameters to be generic classes themselves:

class MyListAlgorithm<TList<>> where TList<> : IList<>, new()
{
    public TList<TValue> DoListStuff<TValue>(IEnumerable<TValue> values)
    {
        var list = new TList<TValue>();
        foreach(var value in values)
            list.Add(value)
        //do list stuff, works with any IList implementation
        return list;
    }
}

The point is to be able to pass in a type constructor as the generic parameter, i.e. a generic parameter that has generic parameters of its own.

Unfortunately this is not supported by the CTS (the CLR type system) at the moment. It would require a complete overhaul of the CLR (just like when generics were first introduced).

(Btw, I haven't made up the SomeType<>-syntax. I just learned the other day that this is how you refer to generic classes in C# today. Classes with more than one generic parameter are written like this: SomeOtherType<,>)

SealedSun