share
Stack OverflowMost wanted feature for C# 4.0?
[+107] [94] Romain Verdier
[2008-09-26 08:59:18]
[ c# .net polls discussion wishlist ]
[ http://stackoverflow.com/questions/138367] [DELETED]

Some blogs on the Internet give us several clues of what C# 4.0 would be made of. I would like to know what do you really want to see in C# 4.0.

Here are some related articles:

Channel 9 also hosts a very interesting video [6] where Anders Hejlsberg and the C# 4.0 design team talk about the upcoming version of the language.

I'm particularly excited about dynamic lookup and AST [7]. I hope we would be able to leverage, at some level, the underlying DLR [8] mechanisms from C#-the-static-language.

What about you?

Romain, next time, make such posts Community Wiki Editable. Such open-ended discussions are not welcome generally. - aku
Copy that. I though you could edit my question anyway... - Romain Verdier
Brilliant question, I was about to ask this and found this readily answered with bunch of useful information. - this. __curious_geek
(3) Voting to close as no longer relevant as C# 4.0 feature set is finalized. - Mehrdad Afshari
I agree with @Mehrdad. - Dykam
(3) Something tells me this question is no longer relevant. - Will
[+116] [2008-09-26 09:04:26] Matt Hamilton

Extension Properties, hands down. I love extension methods and want to be able to ditch the parentheses when they're not appropriate.

Finally I'll be able to type:

var time = 2.Minutes.Ago;

Edit Someone asked me to edit the post with some (hypothetical) code which would enable the above syntax, so here goes:

public static class MyExtensions
{
    // we need the "this" parameter even though it's a property
    public static TimeSpan Minutes(this int i)
    {
        get { return new TimeSpan(0, i, 0); }
    }

    public static DateTime Ago(this TimeSpan t)
    {
        get { return DateTime.Now.Subtract(t); }
    }
}

It is a bit weird, because an extension property would need an argument representing the "this" object. I don't know if the method-like parameter syntax is the best option here, but it feels fairly natural.


An extension property is really just a get/set pair of extension methods and so you could have thought it was pretty easy to add. - Phil Wright
(3) The only benefit from Extensions Properties is - IMHO - their ability to produce clean fluent interfaces, like the one you shown. - Romain Verdier
Wouldn't extension properties have to create a static Dictionary<WeakHandle, T>? - TraumaPony
not if they're read-only - Mark Cidade
(7) True - I think read-only extension properties would be enough. Settable ones would be a bit more complex to implement - more like Extender Providers or Attached Properties. - Matt Hamilton
(27) This makes no syntactic sense. - Rick Minerich
Rick - what do you mean? The "2.Minutes.Ago" syntax is the canonical example for extension properties (and dynamic languages). - Matt Hamilton
The NUnit framework makes extensive use of properties like: Is.Not.EqualTo().AsCollection, etc. Be easier to add your own into the model with extension properties. - sixlettervariables
I wonder if the DLR is going to ship with .NET 4.0? If it does, then I'd imagine you could just program in Ruby and get the coolness of that language. note: I haven't done much with Ruby yet, so I'm not sure if it's Rails that give you that coolness or not. - Chris Pietschmann
(45) What's so wrong with typing var time = DateTime.Now.AddMinutes(-2). It it really that much better to type stuff like 2.Minutes.Ago? Maybe we should all go to Cobol and MULTIPLY B BY B GIVING B-SQUARED. - Kibbee
(18) People think about time in terms of "2 minutes ago" not in terms of "the current time plus negative-2 minutes". That's why it's so much better - Orion Edwards
(16) The problem with 2.Minutes.Ago is that its very English centric. Its said that this is helpful because thats the way we think. It would be more acurate to say thats the way native English speakers think. I agree with Kibbee a mathematical representation is better. - AnthonyWJones
(1) Agree with Rick: it's cool, but doesn't demonstrate why extension properties would be valuable on a large scale. - peterchen
(2) Extension properties are no more "valuable" than extension methods. It just lets me remove the () from the end of the call. It's about readability. - Matt Hamilton
It's amazing how F# does it and seems like they justified it, I mean extension everything, not just properties. - Joan Venge
(7) "2.Minutes.Ago"... Wow. That's some of the ugliest code I've ever seen. - BoltBait
This seems like it would convolute the language. We could end up with things like 2.dollars.plus.tax(5), or something like that. - Nathan Koop
(2) @BoltBait you have a strange definition of "ugly"! How is '2.Minutes.Ago' "uglier" than 'DateTime.Now.AddMinutes(-2)'??? - Matt Hamilton
(2) I'm still lost on why "var time = 2.Minutes().Ago();" is such a big problem. - Matthew Whited
(7) """2.Minutes.Ago"... Wow. That's some of the ugliest code I've ever seen.""" --It seems then that you haven't seen a lot of code. Or that you have a bizarro personal definition of ugly. - foljs
(3) """I'm still lost on why "var time = 2.Minutes().Ago();" is such a big problem. """ -- Are you also lost on why higher level languages are more expressive than lower level ones? - foljs
(1) 2.Minutes.Ago looks like Ruby. (Not a problem, just saying.) - Sarah Vessels
@Kibbee totally missed the point. - Owen
Stop stealing from Rails... - Min
(4) @Min to be fair, I'm actually stealing from an older language which I call "English" ;-) - Matt Hamilton
If you disagree with Rick Minerich, I think you ought to edit your answer to show how you'd (theoretically) declare the extension properties that would allow you to type 2.Minutes.Ago. I was taken aback by his comment, but after considering it, I agree with him. It seems like you'd have to have properties with different types on the get and set. - Kyralessa
@Kyralessa Extension properties would almost have to be read only. Setters would be very complicated to implement. - Matt Hamilton
1
[+114] [2008-09-26 14:38:37] Johan

I would like to declare enums of other types than int, byte, short, long:

public enum MyEnum : string
{
    Value1 = "Value1",
    Value2 = "Value2"
}

And/Or it would be nice if enums could have methods, like this:

public enum MyEnum
{
   Value1 = 1,
   Value2 = 2


   public override ToString()
   {
      switch(this)
      {
          case Value1:
              return "String representation of Value1"

          case Value2:
              return "String representation of Value2"
      }
   }
}

I couldn't agree more, It's super annoying having to cast an enum to a type. - James Hall
More than just simple methods, too - methods which can be overridden by individual values. Basically turn enums from "named numbers" into "restricted set of values with common base type". Java has quite a lot of this, but it's a bit clunky. C# could do better :) - Jon Skeet
Nice idea (+1), but how would you handle flags enums? - Keith
Yes. Something along the lines of value types with explicitly defined instances. It always feels a bit kludgy when I do this sort of thing in C#, ideally there should be almost no syntactic overhead. - Wedge
@Keith, you could use a collection or a composite for flags. Instead of using convoluted bit-wise operations you could use more intuitive set-based operations, e.g. contains, add, delete, etc. It's easy enough to build (de)serialization smarts into the composite so it would fit into 8/16/32/n bits. - Wedge
(3) This feature would be awesome, but it's probably more a .Net Framework feature than a language specific feature. Other .Net languages would need to support it also, not just C#. - Chris Pietschmann
(13) I find it hard to see the benefit of this. Would "public enum MyEnum : string" have only 2 valid values? Oo, how is it different from "public enum MyEnum" - which already has ".ToString()" ? Would the storage be less efficent due to being a string? What is the upside? - Anthony
have you tried writing an extension method for an enum of your type to do your ToString() idea? I think I'll try and see what happens :P - Sekhat
(6) Like Anthony, I cannot see the benefit. This seems like a foolish feature to add. - Judah Himango
(6) This can actually be achieved already (to an extent) with Attributes and Extension Methods. A guy at work had to do it so he had attributes on each enum value and then an extension method ToFriendlyName() which reflected for the attribute. Not 100% the same, but damn close - Slace
(1) I want Enums that don't need to be qualified by Namespace.EnumName when it is clear from the context: enum E { a, b, c }; void Foo(E value); void Bar() { Foo(a | b); } - peterchen
Attributes on enums requires reflexion and is not particularly efficient, I believe. - Benjol
Yes, yes, one hundred times yes. Java's Enums are the one feature I really miss now I'm using C#. I'd love to see this added. - Jon Rimmer
(5) Why not simply use a class with constants only? - Zoman
Well, I can't say that I would want enumerations to be non-numeric. However, I would indeed like a much simpler way to get the string representation of an enumeration value. In addition, I hate dealing with [Flags] enumerations...some built-in static Enum. method or something that made it really simple to check which flags were set would be a HUGE boon. - jrista
(1) Not a guru on enums, but doesn't this break the whole concept of an 'enumerated' type? - amischiefr
Not gonna happen. Enus are value types. You'd introduce MAJOR breaking change - Krzysztof Koźmic
I have to disagree on this one. Enum values are constantly ToString()'d and parsed to their enum names, and this would only introduce confusion. - stimpy77
Don't change the way Enums work - that would be crazy. Do, though, make it easier to get at Attributes. - Dan Diplo
I solve the issue with the .ToString() by using a Description Attribute. - James
While I'm not sure strings are necessary, just today I was wanting to declare an enum of type float. - Kyralessa
This would be more like an immutable dictionary than an Enum. IMHO, enums are nothing but int-based immutable dictionaries. - Evan Plaice
Java already has this feature and comes in handy. - Jeffrey
2
[+103] [2008-09-26 09:06:22] Michael Stum

Optional Parameters.

public string ThisFunctionHad3OverloadsBefore
    (string inputString,
    int desiredLength = 20,
    char desiredChar = 'x',
    bool keepCapitalization = false)

Visual Basic.net has it, so it's indeed not a limitation of .net but of C#. And in the C# 3.0 Compiler, Microsoft introduced Auto-Properties, which also serve absolutely no purpose other than reducing 6 lines of code into 1 line to remove clutter. Method Overloads that do nothing except calling the master function with some fixed parameters are no different than Properties with an "empty" Getter/Setter - they are just unneccessary clutter.

Edit: Good stuff: We get BOTH Optional and Named parameters in C# 4.0.


From what I've read, optional params were deliberately left out of C# because the same thing could be achieved with method overloads. - Matt Hamilton
Yes, and it was a stupid decision because the same could also be achieved using only Assembly and (optionally) a fork. - Konrad Rudolph
(2) They made Auto-Properties just to reduce clutter, so they can as well make Optional Parameters for the same purpose :) - Michael Stum
(3) Coming from a long long debugging session because of optional parameters, I can definitely say that I do not want them in C# 4.0. - Lasse V. Karlsen
(1) lassevk - I'm with you 100% there, optional parameters are the devils own creation and have caused me more headaches than I care to think of. - Rob
Matt Hamilton is right - A language with both overloads and optional params would have problems deciding which of two related methods to call, and complex and non-obvious disambiguation rules would be required. Of the two, the designers of C# chose overloads. I think it was the right choice. - Anthony
I'd rather have overloads than optional parameters. - Keith
(1) Interesting. I see where you're coming from (Overloads allow setting Breakpoints into the function and the stacktrace shows exactly from where you come from), but what are some actual problems? In my mindset, overloads are if you have different logic, not just different parameters. - Michael Stum
I hate optional parameters. - TraumaPony
Overloads are for different parameters, but the logic (apart from handling those params) should be the same - otherwise you get confusion. - Keith
Then overloads would make even less sense. What I mean is: An overload could have additional code to get a value from the database or through some other means first. At the end of each overload, it should call one common function, but I find empty overloads unneccessary clutter, just like priperties - Michael Stum
The way optional parameters are typically implemented (e.g., VB6 (don't know about .Net)) the optional parameter is an indicator to the compiler than when generating a method call that value should be inserted. This has implications for when the value of the default is changed. - Jeffrey L Whitledge
That is, the value is included in the referencing assembly, not the referenced assembly. Of course, this isn't a big deal in the .Net world, since any change to a DLL requires recompiling everything anyway. - Jeffrey L Whitledge
I'm glad they left out optional parameters in c#. Experience tells me that a function using them ends up plagued with checkings that make code less readable. - Trap
using ovptional parameters that compiled into overloads would be okay. If you did void Foo<T>(arg = default(T)) and then tried to define Foo<T>() that should get a compile-time error - Mark Cidade
(1) I'm glad they left out optional parameters, the code is cleaner than VB in this sence. Last week i was working with VSTO and I have tons of optional params I have to replace with Type.Missing... This makes things complicated and hard for people trying to use your code. how can we predict the outcome - Alexandre Brisebois
They had this in C++, too. - Joel Coehoorn
I am so happy they left optional parameters out of C#. - Jason Jackson
Overloads and optional parameters are not quite the same thing. I can see optional parameters being useful, but i'd rather they be left out in favor of the new Property constructor syntax. - sixlettervariables
Optional parameters and virtual functions does not work well together. - dalle
Optional parameters are good because you can can have a single method instead of more and invoke it like so : SomeOfficeFunction(1, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ). This is definitely better than method overloading. Not to mention this kill testability. - Pop Catalin
I'd much rather have named parameters, similar to the way object initializers work now. - Wedge
+1 I still cannot believe they don't have this already. - corymathews
No, no, no! Let's keep C# atleast slightly java/C++ like it origins. This would be as bad as the var keyword being shoved everywhere - Chris S
@Chris S: first ... why is var everywhere a bad thing. I find it helps me program faster. Second you are getting this features (and like the other language features. If you don't like it, then don't use it) - Matthew Whited
saywhat? i thought it got included... - RCIX
3
[+96] [2008-09-26 12:15:13] Jon Skeet

The question has already included a link to my blog, so I'm not going to waffle here, but:

I want better support for immutability. I'm 99% sure I won't get it in C# 4, but that really is my chief request. C# 3 made it easier to create and use mutable types (with automatically implemented properties and object initializers). The same level of support for immutable types would be very nice indeed. It's harder to do, but would be very welcome. I suspect some variation on the builder pattern is required, basically.


(1) Jon, sorry for having misspelled your firstname in the question - it's fixed now. Also, I would like to congratulate and thank you about your very good book. - Romain Verdier
I'm with you 100%. In fact, Eric Lippert has written so many things about immutability that I'm surprised he hasn't yet pushed for more language support. - Konrad Rudolph
Seconded: C# in Depth was a fantastic book - Keith
(2) +1 immutability ftw. - sixlettervariables
I wonder how you can be so sure about the lack of immutability in C#4? It seems likely they intend to bring some more FP into C# and I would have thought immutability would be a key building block to that. - AnthonyWJones
(1) @Anthony: I keep my ear to the ground :) - Jon Skeet
+1 from me. Would love to see a 'readonly' modifier available for type definitions. This would require all fields to be either readonly structs, or readonly reference types that are also defines as readonly. An entire sub-graphy of object references could be enforced as immutable at compile time. - Drew Noakes
Amen. I'm with Konrad, surprised that Lippert hasn't tackled Anders for not including this in C# 4. (So it seems at least, given Anders C# 4 talk at PDC08.) - Judah Himango
Who's to say Lippert hasn't tackled Anders? :) I suspect that the cries for better interop support were just louder when the 4 dev cycle was winding up, that's all. I'm looking forward to immutability as a first class concept in just another version or two. :) - Greg D
(2) Maybe they will do it at the same time as pattern matching and abstract data types... - Ben Lings
Wish I could give that more that one up vote. I'd also like to see more support for immutability throughout the framework, e.g. provide a combination of language changes and API changes that make it easier use XML serialization. Right now, when you want to use certain API features you really have to jump through hoops to use immutable types, often being forced to write a parallel set of mutable types. - Phil
(3) Guys, this is @Jon Skeet's first answer! - Andreas Bonini
4
[+81] [2008-09-26 10:46:20] Matt Hamilton

As a follow-up to Keith's suggestion (#3) for more generic constraints, I'd like to be able to constrain a generic type based on its constructor signature. For example:

public T GetSomething<T>() where T : new(int, string)
{
    return new T(1, "foo");
}

Right now I can use the "new" constraint to tell the compiler that "T" has a default ctor, but there's no way to tell it that T has a ctor with a specific signature.


That would be nice :) - leppie
(1) I wouldl like this, too but there is an issue of intent--you can just assume you want to use a default implementation of T, but what does T(int,string) mean in a generic sense? Is this a kluge for anonymous interfaces? - Mark Cidade
But interfaces can't impose a ctor signature onto an implementing class. From memory I wanted this because simply saying "where T : Foo" isn't enough to let the method use class Foo's ctor signature. - Matt Hamilton
(1) One thing would be to use an abstract Initialize method, to me (my opinion, by all means I can see that yours is 100% valid) it makes the interface cleaner. Ideally, this would actually land up in interface constructors. - Jonathan C Dickinson
(5) marxidad is right. constraining to classes that have a T(int,string) constructor is meaningless, there's no constraint that these constructors have the slightest thing in common. Could be T(maxconnections, urlToConnectTo) and U(listCapacity, fontName) - Anthony
(10) @Anthony - then surely new T() means even less? And yet the language supports that. The point of constraints is to declare what operations can be performed, not to lock down what they ultimately mean. - Daniel Earwicker
I would like to see this for static methods also. No more having crazy logic just to use something like "int.TryParse()" Also I know this can be faked using dynamic types but that just isn't nearly as cool or safe. - Matthew Whited
This. I had to write some fairly crazy that would not be necessary if I could just say "where T: MyBaseType, new(string,int)". - Badaro
5
[+66] [2008-09-26 13:09:07] Torbjörn Hansson

Auto implemented property initializers.

public List<string> MyList { get; set; } = new List<string>();

In this case, you'll want that to be read only. You probably don't want them setting the entire list, just items in the list. - Joel Coehoorn
But then you'll want auto-implemented lazy initializers after that, e.g., public List<string> {get;} = if null(()=>new List<string>()) - Mark Cidade
(1) I just want it to be able to set a default value like you can with private fields. i.e. private List<string> myList = new List<string>(); public List<string> MyList { ... } - Torbjörn Hansson
(4) I dont understand this. Why wouldnt you use public List<string> MyList = new List<string>(); instead - acidzombie24
(13) @acidzombie24 because that would be a field, and public fields are no good. Properties and Fields are not interchangeable. - Rex M
Yes yes yes. This is the most annoying thing about automatic properties. - Callum Rogers
6
[+56] [2008-09-26 13:47:11] TraumaPony

All of the design-by-contract stuff from Spec#.

Seriously, it's awesome.


(4) +1 from me. Especially the ability to specify non-nullable reference types. Not only could this reduce runtime errors but it could improve the performance of method dispatching under certain circumstances. - Drew Noakes
You should include some more information about this stuff in your answer to help spread these ideas further. - Drew Noakes
For those interested, info for Spec# can be found here: research.microsoft.com/SpecSharp - Chris Pietschmann
I agree with you. Spec# could have its features merged into C#. I don't think it will happen, but would be great. - Victor Rodrigues
Amen! I've been bugging the C# guys for a few years now that what developers really need is a way to write less buggy code. The stuff from Spec# like [Pure], [Immutable], DbC, non-null reference types would eliminate swaths of bugs in real codebases. Please, Anders and C# guys, we want Spec# in C#! - Judah Himango
Some of the features from Spec# will make it in, but not necessarily in the same format. There is support for code contracts, which is based on Spec#. - Scott Dorman
Well, actually, it's based on design-by-contract, upon which Spec# is based ;) - TraumaPony
Yes, dbc would be invaluable. - Matt Olenik
(4) Code Contracts will be part of .NET 4. It's language agnostic too! - Steve Dunn
Meh, personally, I really dislike the way it's done. - TraumaPony
Totally agree..... - Joan Venge
(1) The static analysis tool is only for Team Suite editions of Visual Studio, still glass half full and all that... - FinnNk
7
[+49] [2008-09-26 10:21:19] Keith

1) Record/Tuple return variables:

public { string ancestorType, int ancestorId } GetAncestorLookup()
{
    //...do stuff
    return new { ancestorType = var1, ancestorId = var 2 };
}

var ancIdent = GetAncestorLookup();

switch( ancIdent.ancestorType )
{
   ... and so on

2) Implied generics on class constructors [1]

3) More constraints for generics, for instance numeric:

public T SquareRoot<T>( T input ) where T: numeric

//or for collections:

public T Sum<T> ( IEnumerable<T> input) where T: numeric

public T StandardDeviation<T> ( IEnumerable<T> input) where T: numeric

Or possibly ones based on operator overloads:

public T Product<T> ( IEnumerable<T> input, T start) where T: operator *
{
    T result = start;
    foreach( T item in input )
        result *= item;

    return result;
}

Or ones for enums [2]:

public static bool IsSet<T>( this T input, T matchTo ) 
    where T:enum //the constraint I want that doesn't exist in C#3
{    
    return (input & matchTo) != 0;
}

4) Internal (rather than private) anonymous types.

5) Strong (built into reflection) support for duck-typing. I want

object someObject = //...
IExpected duckTyped = Reflection.Get<IExpected>( someObject );

//or even
duckTyped = someObject as IExpected;

if( duckTyped != null )
   duckTyped.InterfaceMethod();

This would work whether someObject's actual type implemented IExpected or not, so long as it could.

6) Equivalent for ?? on properties of nullable objects [3]

[1] http://stackoverflow.com/questions/45604/why-doesnt-c-support-implied-generic-types-on-class-constructors
[2] http://stackoverflow.com/questions/7244/anyone-know-a-good-workaround-for-the-lack-of-an-enum-generic-constraint
[3] http://stackoverflow.com/questions/123088/possible-pitfalls-of-using-this-extension-method-based-shorthand

It was a delibrate choice not to have anonymous return types as your first point is. I believe the reason was because it is an unnamed type and these are not supposed to be thrown around the program in this way. In Software Engineering Radio (www.se-radio.net) episode 97 Anders Hejlsberg explains it - Morten Christiansen
Yeah, I was familiar with that - perhaps that example should be internal. - Keith
Still - they let you pass around generic classes that wrap anonymous types. After all, that's what the Select extension method does - return an IQueryable<T> where T can be an anonymous type. - Matt Hamilton
oh my god yes to #6 that gets me all the time! Thank god for unit tests - George Mauer
(2) I'd love to have typed tuples/records. - Thomas Danecker
I wish you'd posted these as separate answers so I could have voted individually :( Some nice ideas though. - Drew Noakes
(2) Re 3 & 4, see www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html - you can have this today with .NET 3.5 - Marc Gravell
Thanks (interesting link), but that really isn't the same thing. Nice workaround though. - Keith
(4) Support for tuples will be in the CLR for .NET 4.0. - Scott Dorman
Except that for some bizarro reason tuples have been implemented as classes instead of structs :/ - Porges
8
[+47] [2008-10-26 15:35:23] community_owned

Non Nullable Types:

public void AddItem(string! notNull)
{
  //notNull is never Null;
}

Constraints:

public void SetAge(byte value)
{
   ///? value > 0 && value <= 100;
}

Unit Testing integration:

public string Foo()
{
  string s = "SomeString";
  return s;

  ///? string.isNullOrEmpty(s) == false s.Length >= 5;
}

In your second example you're discriminating a lot of older people :P But yeah, Constaints and Non-Null would be superb. - Michael Stum
=D lol you're right. I should release a service pack for my code ;) - community_owned
I think were getting Contract in .NET 4.0. But I still want my Spec# language integrated contracts!! - jrista
+1 for the non-nullable thing! - erikkallen
9
[+42] [2008-11-06 22:54:19] MrSlippers

I've always wanted "private" property members, such that you could write:

public int MyProperty
{
    int _myProp = 0;
    get
    {
        return _myProp;
    }
    set
    {
        // Do some fancy set logic
        _myProp = value;
    }
}

Yet I don't want _myProp to have scope outside the property. Therefore I could guarantee that all internal users of the field used the property and therefore used the set logic.


(1) From a scoping perspective, this makes more sense to me. After all, from a design perspective, you generally always want to modify the member variable through the property (unless doing so is cost prohibitive). - Mike Hofer
(3) You don't always want to use the setter. Sometimes may do extra work that you only care about when called from outside the class. But the ability to add this to your toolbox would be nice. - Joel Coehoorn
I'd love this with the addition that are private in the class scope, not private in the property scope, so within the class you can call MyProperty._myProp - Davy8
You can probably use PostSharp to hide the backing field... - Dmitri Nesteruk
You can achieve this via wrapping the field in a class instance. All mutations/accessing is then pushed through this instance. I.e. nobody can do the 'wrong' thing because you explicitly stop them from doing the 'wrong' thing -- they must go through the wrapper instead. It's not particularly elegant, but it will do the job. - Mark Simpson
Totally agree with this one. I've wanted something similar to this for a while - would be very handy for enforcing class invariants, concurrency protection etc. At the moment, you're limited to simply documenting the invariants for member variables, but with this you can enforce the invariants. In theory, anyone altering/writing code for the class should be aware of these invariants, but even if you wrote the code yourself, you sometimes forget about them. (Personally, I use code comments on member variables that have important invariants, but this would be much better). - Phil
10
[+35] [2008-10-01 08:57:47] Torbjörn Hansson

To be able to write binary values:

int myInt = (int)%00011011 | (int)%11111110 | myOtherInt;

Ooh. That's a fun concept!!! - Jonathan C Dickinson
(1) For C++, this was suggested, using the syntax 0y010101010 (compare 0x1234 for hex; the suggestion noted that "y" is the last letter of "binary", as "x" is the last letter of "hex"). Unfortunately, it was not adopted. - James Curran
+1 for this. Would love to see binary literals. For many low level operations they are much more expressive than their hex equivalents. Furthermore, I can't see any reason why these shouldn't or couldn't be included. - Drew Noakes
why not just implement a utility function to do it? Wither a varargs verion binary(0,1,0,0,1,0,0,1,1,1,0) or some clever int parser binary(1101001110101)? - John Nilsson
Oh, please, no! In my 6 years of C# coding, I've never had a use for such a thing. - Judah Himango
this is soo useless, hexadecimal literals is enough to work with bitfields after you get used to it. - Pop Catalin
F# has this: fsharpdotnet.com/fsharp-literals - Mauricio Scheffer
(3) Well, if someone hasn't had a use for a feature in 6 years, it can't possibly be useful. Um, by the way, I've been coding for a while now, and I've got a big list of things they should get rid of since I don't use them. - Beska
(3) You should try embedded programming (.Net Micro Framework), flags, and socket/device code. You would see how nice playing with bits can be. Right now I have extension methods and special structs to make some of these ideas possible. But language support would be much nicer and faster. - Matthew Whited
Heck, you could make some extension methods to take binary numbers as strings so you could pass in "10110010" and the like; but it would be much more convenient to be built into the language. - Kyralessa
@Kyralessa: so we arn't going for speed then. (embedded normally means less memory and power) I'd rather stick with doing hex conversions in my head then converting "binary strings" to integers - Matthew Whited
(1) Those of us who do lots of bit work would love this. Everybody else can not use it. There's probably a massive amount of coders who never use hex numbers, for example, and they don't go complaining that they should be removed! - Will
11
[+33] [2008-09-26 10:52:25] Adam Wright

A longer delay between releases.

Seriously, programming languages are not console Football games - we don't need a new roster each year. What we do need is a period of stability, so the community can learn to understand what's already in the marketplace. It's at the point where you ask "Do you know C#", and actually, it's a meaningless question. Good 1.0 is not good 2.0 is not good 3.0, yet they've all appeared in about 5 years. Even here, I find it hard to provide sound example code to questioners who've not specified their version because the reasonable methods are so different between each.


(51) I disagree. Give me new language functions every year - I can keep up and I expect professional developers to do so too. This rapid progression right now is C#'s big advantage over Java - MS should push it while they can. - Keith
(1) I read your answer out loud to my coworkers, and they all laughed and agreed with you whole heartedly. - Joshua Carmody
(6) Especially if you target desktop applications. It's hard to always ask a client for an update of .Net by every upgrade. Specially if they have an IT department that wants to test everyting. - GvS
(1) I agree with Keith, the development speed is OK - get us a new release every 2-3 years, we can deal with that. - Borek
I'd like to see the new features every year, but done in a more-extensible way. A for-free addon for visual studio and 5Mb (instead of 50) download that patches rather than replaces an existing install, for example. - Joel Coehoorn
(7) The libraries can update every 2-3 years just fine. But the core language is moving way too fast. I have 20 year old C and 10+ year old C++ code that still compiles clean and I understand the syntax. 7 Years of C# and my original code looks totally different than what I write today. - Jason Short
(1) On language features, I disagree. On development paradigms, I agree 100%. We've barely gotten really good at ASP.NET and WinForms, and now along come ASP.NET MVC and WPF! :O - Kyralessa
It should be noted that ISO requires 10 years between changes to one of its standards. - James Curran
(5) @ Kyralessa, they ain't dropping winforms or webforms, So stick with them until you find a good reason to switch, all MS is doing is providing new tools to attack problems from a different angle, not replacements in how it's already done. - Sekhat
+1 for Keith's comment, Before C# 3, I wasn't nearly using as much functional-styled code because it always looked so weird. - Mauricio Scheffer
(1) It seems to me that these arguments stem from a feeling of wanting "the best" all the time. - Matt Olenik
(2) >> @JShort: "I have 20 year old C and 10+ year old C++ code that still compiles clean and I understand the syntax. 7 Years of C# and my original code looks totally different than what I write today." Yes, but your C# from 7 years ago still compiles. They are adding features, not replacing them. - Paul Stovell
(8) Just because someone 'hasn't completely mastered' the language is no reason not to add features. The lack of a warm fuzzy is no reason not to develop the language. As above have indicated... there are no features removed... - jle
(2) I agree. It would be far better if they got each technology better polished before they released them, particularly in the documentation department. For example, wouldn't it have been better if they had made LINQ to Entities right in the first place, rather than wasting our time with LINQ to SQL? - Martin Brown
(5) I disagree, the rapid evolution of C# is its power. If you code looks different, it's because C# add powerfull features that you can't live without... Features are used by developer BECAUSE they are useful ! - Nicolas Dorier
(4) I have to disagree too. The regular and continual progression of C# is continually making it a better, more flexible, more powerful language. Its just more tools in my toolbox that help me solve difficult problems with less effort in more elegant ways. I say keep the improvements coming, Microsoft!! GG! - jrista
Might be controversial but it feels like it bloats with every iteration. - Skurmedel
@Skurmedel: then don't use the new features - Matthew Whited
One thing to note is that though the C# language has been "changing", the CLR has not -- still 2.0 (for now). So all of these new features are either language facets for preexisting CLR mechanisms or syntactic sugar. - Travis Heseman
12
[+28] [2008-10-01 17:39:22] community_owned

Anonymus enum-parameters

Dont even know if the term exists or if it's accurate, but i thought something like this would be convenient:

void SetUserStatus(status={User, Admin, Banned})
{
  if(status==User)
    DoStuff();
  ...
}

This way you don't have to declare an enum that uses at least 5 lines of code every time you want an enum that only is used for one function.


(2) I imagine this would be confusing for the parser. Calling code would look like: obj.SetUserStatus(User); ...it wouldn't be clear to the parser what this symbol meant. - Drew Noakes
Drew, I think this could be great. To avoid this confusion, we could use the parameter name as the enum name, like status.User , status.Admin. - Victor Rodrigues
I agree. It enforces the principle that properties should be discoverable, but doesn't force you to make a whole new enum for something that's only used by one method. - Kyralessa
(3) This is a GREAT idea - acidzombie24
The idea is great, but I can't see how it would work. For example, how would you create a local variable of that type (inside SetUserStatus or in the function calling it)? Or can you only pass constants to SetUserStatus - that sounds like a severe limitation. Can SetUserStatus pass status to another method "SetUserStatusInternal", or would you have to cast it around? Unless C# gets a far more sophisticated type inference, I can't see how these problems could be solved. - nikie
auto as a type ala c++? This would still be so cool, even if you needed a named enum for various usecases that nikie outlined. - Will
I assume that if you wanted to set variables to type status, you'd need to declare an actual enum. This syntax would be just in cases where you're never going to need to do that. You could also start with this kind of method-contained enum, and later pop it out into an actual enum if you saw the need. I always hate having to create a new enum for one method, and then having to worry about its visibility and so forth. - Kyralessa
13
[+27] [2008-09-26 10:11:57] Rob

My candidate would have to be point 4 from the anastasiosyal.com reference [1], "Safe Null Dereferencing Operator" .. The elegance that this could introduce in code that I've both written and seen is boggling. So that'd be my candidate for a most wanted feature for C# 4.0!

[1] http://anastasiosyal.com/archive/2008/07/19/4-features-for-c-4.0.aspx

I tried to do a generic extension workaround for that: stackoverflow.com/questions/123088/… - Keith
It would be very cool if they would implement this functionality with a Maybe Monad ;) - Thomas Danecker
Null-safe dot notation -- nice! I'd prefer a single symbol though, like: int? orderNumber = Customer!Order!OrderNumber; - Travis Heseman
Mostly obsolete if they'd include non-nullable types, but still a good one. - Joren
14
[+23] [2008-10-29 16:46:13] Chris Ammerman

A modifier keyword for function argument (or variable/field) definitions that indicates a reference type argument must be non-null.

I have so much null-check code in my apps, it would be awesome to just sweep it all away with a single declaration modifier.

As an example, this:

void MyFunc(Object x, Object y)
{
  if (x == null)
    throw new ArgumentNullException("x");
  if (y == null)
    throw new ArgumentNullException("y");

  // Do stuff...
}

Could become this.

void MyFunc(nonull Object x, nonull Object y)
{
  // Do stuff...
}

oh Yeah. I would LOVE to have this. - StingyJack
I'd love this, too, but I don't see how to implement it, since the compiler often can't know if a reference is null at compile time, where you would want to make that check. - Joel Coehoorn
(6) I don't want a compile-time check, I want a run-time check. I just don't want to have to write the same exact code over and over again, since all that changes is the variable name. The compiler could generate IL to do this for me. - Chris Ammerman
Well, you could certainly write a single function with a params argument, which would at least mean only one line of code per method. Something like: ThrowIfNull(x, y); where the method signature is void ThrowIfNull(params object[] parameters) - Kyralessa
I've got a ThrowIfNull extension method on Object now that I use, but it's still more verbose than it seems it needs to be. - Chris Ammerman
Why shouldn't the compiler be able to check this? It already checks if local variables are initialized before they are used, all it would have to do is check if all members are initialized in each constructor, too. Plus every assignment from a nullable variable to a non-nullable one should require a cast that can fail (similar to nullable value types) - Niki
Great suggestion. I would even go a step further and say that every variable/member/parameter should be non-nullable by default, just like with value types. - Niki
Non-nullable types as Spec# does them are perfect. - Joren
15
[+20] [2008-09-26 13:38:07] Andre Bossard

I'm a nostalgist:

System.Error.BlueScreenOfDeath.Appear();

Amusing........ - JJC
You should follow MessageBox-like notation, so your line should read System.Windows.Forms.BlueMessageBox.Show() - Dmitri Nesteruk
@Dmitri, BSOD does not follow a MessageBox like notations, as it isn't a MessageBox or anything like it.... - Andre Bossard
There is a Screen class. So maybe something like System.Windows.Forms.Screen.BlueOfDeath.Show(). - Kyralessa
(7) This would imply that we need access to the System.Error.BlueScreenOfDeath namespace, when we all know that the BSOD is ever-present. A globally available BlueScreenOfDeath(string crypticErrorMessage, int insanelyLowDisplayTime) method would suffice. - JoshJordan
lol is not allowed but really - it applies in this case. - Barry-Jon
(2) BSODs are reserved for kernel errors. There is very little, if any, software that should be allowed to take over your OS. Gooood luck. - tsilb
16
[+20] [2009-05-28 13:16:36] Martin Konicek

Have you ever been annoyed by having to write property or method name in quotes? eg.

// define a rule for Person.Age
var r = new Rule(typeof(Person), "Age", ...)

This is error-prone, and results in run-time errors.

What about?

var r = new Rule(propertyof(Person.Age), ...)

When we have typeof, why not have propertyof and methodof with the same benefits? IL even supports this now, it's just not supported in C#.


I use Property.Get<Person>(() => p.Age), which is better than strings, but I agree this could be better. - Andrey Shchekin
Property.Get looks at ()=>p.Age as Expression tree and gets the string "Age" out of it, right? I'm using something similar: dotnet.dzone.com/news/silverlightwpf-implementing - Martin Konicek
Thats called the infoof operator and it almost got in c# 4. blogs.msdn.com/ericlippert/archive/2009/05/21/… - gkdm
Eric Lippert makes an excuse that it would be hard to implement for methods. Why not implement it just for properties? That should be easy and very very useful feature. - Martin Konicek
17
[+19] [2008-09-26 12:18:49] GvS

Named parameters

Reading code with calls to methods like MessageBox.Show, will be much more clear


(4) Sounds like you'll get your wish - Anders announced at PDC08 named parameters will be in C# 4. - Judah Himango
Hey great, that's the only thing I missed moving from VB to C# - GvS
Yes, named parameters will be in C# 4.0. - Scott Dorman
18
[+18] [2008-09-26 10:58:17] morechilli

Better handling of IDisposable objects.

Managed c++ removes many of the headaches associated with IDisposable classes through stack style semantics for reference objects and destructor = Dispose implementation with automatic chaining.

C# would be a better language if it went that way too.


(6) Why not just "using"? - Marc Gravell
(1) Using can only be used for local scope - useless for member variables. Managed c++ copes well with IDisposable members. - morechilli
Agree 100% with this. incrediblejourneysintotheknown.blogspot.com/search/label/… - Daniel Earwicker
When you're "using" more than one object it also looks ugly too! Would love the C++/CLI way of doing it in C#. - Ray Hidayat
I tend to Debug.Assert in the finalisers of my IDisposable objects. See stevedunns.blogspot.com/2009/03/idisposable-alerts.html for more info. - Steve Dunn
(3) It should be possible to using with a non-disposable object (of course, it wouldn't mean anything), but it would be nice not to have to care about whether classes implement IDisposable. - erikkallen
(2) +1 for erikkallen. Making value types and non-IDisposable objects compatible with the using statement also helps prevent issues associated with API changes say where a type becomes IDisposable at some later date. If the using statement was already being used to declare a lifecycle scope for the instance then no compatibility break would result. - jpierson
19
[+16] [2008-10-21 18:47:25] Krzysztof Koźmic

Three things.

  1. Design By Contract Spec#-like features (and I truly hope it will make it to the C# 4.0 in some form)
  2. field contextual keyword within properties Many times I don't want to be able to set a field directly, but only through it's property, even from within the class. Common example would be - I never want the field to be null
public string Name
{
   get {return field;}
   set
   {
      if(value==null)
         throw new ArgumentNullException();
      field = value;
   }
}
  1. Additional feature to Design By Contract - interceprion mechanism baked into the framework So that I can have injected a pre/post call logic to a method. This is however a long shot, and I don't think we will get it... It would be great however if it became a part of the framework, as it could be balzing fast then.

#2, you're basically talking about an automatic backing store? - Joel Coehoorn
#1 seems to be getting there: 74.125.47.132/search?q=cache:9WUmCLcCM-cJ:blogs.msdn.com/… - ILoveFortran
Sorry, that was the cached link; here is the real one: blogs.msdn.com/bclteam/archive/2008/11/11/… - ILoveFortran
#1, well - yes, and I'm happy about it, thought the way it is implemented makes it much less powerful than it could be when more tightly integrated with the runtime. - Krzysztof Koźmic
20
[+16] [2008-12-29 20:06:24] ILoveFortran

Adding an IArithmetic interface, which would be implicitly implemented by numerical primitives (int, double, etc). Currently it is not possible to do numerics with generics - you cannot even define a generic method like T add(T x, T y).

See also: Feedback ID 94264 on Microsoft Connect [1]

[1] https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94264

Or, better, something akin to C++0x's concepts. Defining a concept and then using that to constrain template type arguments. WoUld validate against signatures even without a common base type. - Richard
21
[+13] [2008-09-26 12:51:08] SeeR

Much much better type inferrence for generic methods.
Example: F#

I dont want to use <,,,>() and make the code less readable when compiler can easily deduct the types from method parameters.

Edit: Example in c# 3.5 that should work:

I have method

public static TResult Aggregate<T, TResult>(IEnumerable<T> elements, Func<TResult, T, TResult> Aggregator){...}

and another

public static string CSV(string s, string s1){...}

so for me this should compile

string[] parts = "aaa;bbb;ccc".Split(';');
string result = Aggregate(parts,CSV);

but it's not, and I must write

string result = Aggregate<string, string>(parts,CSV);

(2) C#3 already does this, if the type can be inferred from the parameters it can be skipped. - Keith
Yes! Especially true for type deduction from method group arguments which currently doesn't work at all, compared to deduction from delegate arguments, which does. - Konrad Rudolph
@edit: I agree (see my above comment). However, there's actually a “good” technical reason why this doesn't work. However, this should go into another question. - Konrad Rudolph
Why can'y you use the Linq method: parts.Aggregate( ...) ? - Keith
But this is more of a "getting an existing feature to work right" rather than a new feature. - James Curran
22
[+12] [2008-09-27 22:06:08] Hamish Smith

Given that everyone hits [1] issues [2] with generics and things that should just work intuitively, I'd say that some implementation of contravariance / covariance for generic types would be great. If the types could be inferred by the compiler / runtime that would be brilliant, if I need to specify some syntax like in java, fine.

Eric Lippert has a great series of posts on this [3] and even suggests some syntax options (and asked people to vote for their favorite).

[1] http://stackoverflow.com/questions/110121/logic-and-its-application-to-collectionsgeneric-and-inheritance
[2] http://stackoverflow.com/questions/124325/net-generic-method-question#124514
[3] http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx

Given the amount of work and thought he's obviously put into this, I'll be very surprised if it's not in C#4. - Joel Coehoorn
I hope so, but hey, I'll keep mentioning it whenever I can and sending people to read the articles 'cos they are fantastic and if there is a lot of noise/traffic about it the feature could get a higher priority. - Hamish Smith
If you've watched the recent PDC 08 talk by Anders Hejlsberg, you'll see C# 4 will indeed have co-variance and contra-variance for interfaces and delegates. - Judah Himango
Yeah, saw that. Very cool. Looks like it will solve the majority of peoples headaches without them realizing it's there at all. Things will just work the way they 'intuitively' should. - Hamish Smith
contravariance and covariance. Check! - Pop Catalin
For interfaces and delegates, but not classes ... which makes sense since fields are inherently invariant. Combined with language support for immutability it could make sense for properties and fields of immutable types to be covariant. - Joren
23
[+9] [2009-01-08 21:19:05] Andrey Shchekin

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 [1]

Nice to have:

  • AddRange support in read-only collection initializers
  • TThis pseudo-type in generic constraints (or even full JavaGI [2])
  • 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".
[1] http://kirillosenkov.blogspot.com/2007/10/yield-foreach.html
[2] http://homepages.cwi.nl/~ralf/JavaGI/

Could you explain "methodof/propertyof"? Also, ?(a.B.C) can be done right now with a fairly convenient syntax. - Mauricio Scheffer
propertyof(Type.Property) -- returns safe reference to property (safe as in "does not compile if property is renamed"). It can be done now with something like Property.Get<Type>(t => t.Property), but it is slower and not built-in. - Andrey Shchekin
For ?(a.B.C) I have seen only lambda-expression solutions. These are ok, but having a faster and easier way in the language itself seems very convenient for the feature that is useful almost everywhere. - Andrey Shchekin
I can't quite figure out what you mean by the &&=, ||=, and ??= operators - RCIX
&&=, ||=, and ??= should be shortcuts for &&, || and ??. The same way &= is a shortcut for & and += is a shortcut for +. - Andrey Shchekin
(1) Upvote for generic attributes. Needed those recently. Other points ain't bad too. :) - Arnis L.
(2) what do you mean by generic attributes? - acidzombie24
(1) Something like [TypeConverter<EnumConverter>] instead of [TypeConverter(typeof(EnumConverter))]. - Andrey Shchekin
I'd like compile-time checked format string implementation, not sure if that would require a change in syntax or not but regardless it would be nice to know that it is being done without string parsing at run-time. The difficulty here however is with many localized applications where most strings are located in some generic data store and thus are not compiled. Compiling these similar to how Regex are compiled would probably suffice. - jpierson
24
[+7] [2008-10-01 09:17:23] Quibblesome

How about adding nothing? Or perhaps even taking something away! :O

We espouse simplicity yet we never seem to apply it to our own languages.


Can't take away--it'll break backwards compatibility. - Mark Cidade
I'm pretty sure the part about "taking something away" was a joke. - Tom
(1) Seriously, C# is rapidly turning into C++ with its everything and the kitchen sink mentality. KISS! - David
25
[+7] [2008-09-26 12:13:28] Chris Ballard

I would like to see some of the Design by Contract principles as a first class language feature, perhaps leveraging on method attributes which can instruct the compiler to wrap the method call with code which runs before and after execution (aka AOP)

EDIT: I had a useful chat with Anders at the PDC following his Future of C# talk [1]. He told me that they don't currently have an extensibility mechanism planned for C#, but the fact that a later C# variant will include the ability to call into the compiler means it would be fairly straightforward to decorate code with your own markup, and write a preprocessor which calls into the compiler and augments the code being compiled with whatever you like. Pretty much like IL-weaving, but done at the source level.

Still not ideal, as the debugging story would be flawed, just as it is with IL-weaving, because the source file no longer matches the compiled objects.

[1] http://channel9.msdn.com/pdc2008/TL16/

Spec# from MS research is a superset of C# which aims that, maybe it will be included as first class language feature one day. - Romain Verdier
Shame that Spec# is stuck as a superset of C# 2.0. Would be good to see these ideas brought mainstream by MS. I especially like the non-nullable reference types. Eg: "string! s = null" is not allowed, and method params having types with ! suffix could never have a null value at runtime. - Drew Noakes
I'm in agreement with Drew. Spec# has proven to eliminate classes of coding defects through it's design-by-contract features and amplification of the type system. It's time this Spec# research project is moved into C#. Please Anders and company, schedule this for C# 5 if it's too late for v4. - Judah Himango
26
[+7] [2008-09-26 16:04:20] leppie
public static T CallWithCurrentContinuation<T>(Function<Continuation,T> cc);

What would you need this feature in a procedural language for? - Konrad Rudolph
I think it would be pretty cool to have call/cc - Mauricio Scheffer
Could you provide a little more information about this feature in your answer? - Drew Noakes
@Konrad Rudolph this is useful when code runs at a specific interval (60 Hz) and you want to spread the execution of code over a number of ticks. Or cooperative multitasking. Currently you can fake it the hard way using iterators and the yield keyword but that's kinda, very, painful. - Jasper Bekkers
27
[+7] [2009-05-25 02:47:24] LBushkin

Generic constraints against primitive numeric types. For example:

public T SumValues( T first, T second )
  where T : numeric  
 // or alternatively: where T : anyof(int, uint, decimal, float, ...)
 // or alternatively: where T : hasoperators(+,-,etc...)
{
   return first + second;
}

28
[+6] [2009-12-11 14:56:42] Martin Konicek

All events should be weak events [1] by default.

Now, if A listens on B, existence of B prevents A from being garbage collected, ie. you can't be collected just because you are listening to someone.

[1] http://www.codeproject.com/KB/cs/WeakEvents.aspx

Actually when using anonymous functions (event += delegate { ... }) the event should not be weak. This is because noone else has a reference to the delegate, so it would get collected and stop working. - Martin Konicek
29
[+6] [2008-09-26 09:13:05] Konrad Rudolph

It's too late now but instead of LINQ [1] I would have loved to have seen some kind of list comprehension (such as in Python or Haskell). It has the same expressive power but uses a more lightweight syntax.

[1] http://en.wikipedia.org/wiki/Language_Integrated_Query

LINQ query comprehensions are in the same style as Python list comprehensions and Haskell's monad comprehensions. In fact, with more than one from clause, they are monadic (SelectMany() is the bind opearator). - Mark Cidade
I object to the unnecessary syntax, not the semantics. I didn't touch on the subject of monads at all. - Konrad Rudolph
Once again, F# has this: langexplr.blogspot.com/2007/02/… anexperimentinscotch.com/?p=450 - Mauricio Scheffer
can you live a simple example (perhaps in python) - acidzombie24
30
[+5] [2008-09-26 15:50:58] Mauricio Scheffer

Traits. In fact, there has been research about implementing it in C# a couple of years ago (http://www.iam.unibe.ch/~scg/Research/Rotor/index.html)


yes, I guess BlueScreenOfDeath.Appear is more helpful than this. - Mauricio Scheffer
31
[+5] [2008-10-10 13:07:07] Pop Catalin

Not a C# 4.0 feature per se but more of a CLR 3.0 feature.

Generic types that inherit type parameters :

public class SignalStream<T> : T, ISignalZeroRead where T: Stream {
     public override int Read(byte[] buffer, int offset, int count)
     {
        int read = base.Read(buffer, offset, count);
        if (read == 0)
            SignalZeroBytesRead();
        return read;  
     }
     public void SignalZeroBytesRead() {
         ...
     }

Usage example:

 var s = new SignalStream<NetworkStream>();
 var f = new SignalStream<FileStream>();
 var m = new SignalStream<MemoryStream>();
 etc...

This can be very useful if you want to extend for example the winforms controls and don't want to subclass a few dozens of them just to implement some interface or add a functionality.


IMO traits or mixins are a cleaner solution - Mauricio Scheffer
(1) @mausch, not if you try to create monads ;) - Pop Catalin
32
[+5] [2010-06-15 21:18:55] Reddog

I hope this isn't already in there, but I just stumbled back across a teeny tiny annoyance such that when using out parameters for a method you need to have the variable holder declared already.

It would be nice to use a method with an "out" parameter and declare it at the same time (ideally using the var keyword).

// Function
public bool TryParse(string value, out int value)
{
    ...
}

// Caller
if (TryParse("123", out var value))
{
     ...
}

As opposed to the current calling code:

// Caller
int value;
if (TryParse("123", out value))
{
     ...
}

NOTE: Please correct me if I'm wrong and it's already in there!


(3) Perhaps a better alternative is to take the F# route: any method that returns multiple values (via return + 1 or more out values) is transformed by the compiler into a method that returns a single value of type Tuple. For example, TryParse would take a single parameter, value, and return a single value, Tuple<bool, int>. - Judah Himango
I like both solutions, I'd learn towards Reddog's first since that scoping is very well known with the using statement already. - Chris Marisic
33
[+4] [2009-05-28 13:40:23] Martin Konicek

Better internal keyword.

Internal now only works at assembly level. I would like to be able to make more specific access restrictions:

  • to restrict access only to types in the same namespace
  • to restrict access only to particular types

Why do I need that? For cleaner encapsulation. I don't want to divide my project into many assemblies, yet I need eg. to have a class that is read-only to the outside, but only special "friend" builder class can modify it. See C# builder pattern [1]

Scala programming language supports this.

[1] http://www.c-sharpcorner.com/UploadFile/rmcochran/instantiationBuilder06232007171715PM/instantiationBuilder.aspx

34
[+4] [2009-06-27 06:12:05] this. __curious_geek

I wish I'd be able to create attributes that can be applied to specific class types only. So when I create an attribute I should not only be able specify that it can target to Classes but also the Type of the class to which it can be applied.

creating an attribute that can only be applied to any class that derives from a given class.

Secondly, I should be able force attribute application, If the class derives from a particular given 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 logistics in base class or derived class.. It must be inherently supported by the Attribute.

This could be very much helpful when you are developing your own framework.


excellent idea - acidzombie24
Yeah, I was building a framework too and exactly this came up... stackoverflow.com/questions/4959863/… - TDaver
35
[+4] [2008-11-17 21:20:00] Danny Varod

Automatic dependency & notifiable properties and simpler syntax for dependency properties:

class MyNotifyingClass : INotifyPropertyChanged
{
    Object MyProperty
    {
        get;
        set; // this should automatically invoke ProperyChanged
    }
}

class MyDependencyClass : DependencyObject
{
    [DependecyPropertyAttributes(DefaultValue = Null, OnChanged = ...)]
    Object MyDependecyProperty
    {
        set;
        get;
    }
}

36
[+4] [2008-11-18 20:54:47] Danny Varod

Static extension methods - extension methods for classes themselves, not only for objects.

public static class MyExtendingClass
{

// Regular extension method
public static void Save(this String st, String filename)
{
    // writes st to filename
}

// Static extension method
public static String Open(static this String, String filename)
{
    // returns string read from filename
}

// Extension constructor
public static MyDataType(static this String, String filename)
{
    var data = new MyDataType();
    MyDataType.LoadStateFrom(filename);
    return data;
}

} Usage:

String st = String.Open("myfile.txt");
String.Save("yourfile.txt");
MyDataType data = new MyDataType(filename);


This can be done with F#: weblogs.asp.net/podwysocki/archive/2008/09/09/… - Mauricio Scheffer
Not sure about the syntax - "static this" is kind of an oxymoron.. - Blorgbeard
(1) I know, it is just an example of expanding the existing extension method sugar-syntax to classes and not just objects. Any other sugar-syntax would acceptable. - Danny Varod
37
[+3] [2008-11-07 15:32:42] community_owned

Instead of this:

string address1 = "";
if (person != null && person.Address != null && person.Address.Address1 != null)
    address1 = person.Address.Address1;

I want to be able to write this:

string address1 = person?Address?Address1;

Or something to that effect.


Something very similar can be easily done right now with Func<T>s - Mauricio Scheffer
I tend never to prime variables and then overwrite the value. In C# it should be discouraged unlike C++ to initialize local variables since doing so hides logic bugs. Also, if your seeing a lot of code like this it may be worth while to read up on the Law of Demeter which is a more philosophic solution to the problem. - jpierson
38
[+3] [2008-10-08 11:39:13] Jonathan C Dickinson

Having a Me generic type in all classes. For example I currently have the following:

public abstract class Foo<T> where T : Foo
{
     public T Activate();
}

Meaning I have classes like:

public Bar : Foo<Bar>
{
   public override Bar Activate();
}

It would be nice to say something like:

public abstract class Foo
{
  public abstract ?Me Activate();
}

A further feature would be:

public class Foo where ?Me : new()
{
   private Foo ActivateNew()
   {
      ?Me result = new ?Me();
      result.Initialize(...);
      return result;
   }
}

I'm a little confused as to the benefit of this. Why do you need the circular genric reference? Why do you need to constrain the class that you're declaring? - Keith
It's complicated, and I haven't found another way to do it. Explaining it would require an article (never mind a comment) and would disclose IP. In a nutshell it comes down to avoiding massive amounts of casts. - Jonathan C Dickinson
What would ?Me be?? I'm not following why you would use this? - Chris Pietschmann
In the case of Foo ?Me would be Foo. When a class inherits from Foo (e.g. Bar) ?Me would be (on both Foo and Bar) Bar. This could be acheived (transparently) using the pattern I described at the beginning. - Jonathan C Dickinson
it's a bit later on, I know, but cloning is a good example of this. The signature would read public ?Me Clone() - Jonathan C Dickinson
Similar feature (This) is described in JavaGI document, take a look at it. - Andrey Shchekin
Hmm... interesting Andrey. I will definitely read up on it. - Jonathan C Dickinson
It's not exactly the same but somewhat related to an idea I had to introduce a new keyword to act as a shortcut to the current type. connect.microsoft.com/VisualStudio/feedback/… - jpierson
39
[+3] [2009-05-23 00:38:01] Evan Moran

I would like to see full Microsoft support for C# / .NET / CLR on all popular hardware platforms.

I understand Mono [1] does this (and I am very grateful), but having Microsoft directly support the project would be a big deal as well.

[1] http://en.wikipedia.org/wiki/Mono_%28software%29

40
[+2] [2009-05-25 02:38:18] LBushkin

Automatic interface implementation through object delegation. For example:

class MyCustomCollection : IEnumerable
{
   // All methods/properties of IEnumerable delegated to m_Strings
   private List<string> m_Strings provides IEnumerable;
}

instead of:

class MyCustomerCollection : IEnumerable
{
    private List<string> m_Strings;

    IEnumerator IEnumerable.GetEnumerator()
    {
        return m_Strings.GetEnumerator();
    }
}

41
[+2] [2009-09-25 13:25:02] Travis Heseman

Maybe not "most wanted" but it's on my list. Anonymous interface implementation.

For example:

// C#

interface IRunnable
{
    void Run();
}

var runnable = new IRunnable()
{
   public void Run()
   {
      Console.WriteLine("Running...");
      // Do your running
   }
};

runnable.Run();

that's crazy, I like it... - Steve
42
[+2] [2009-06-11 23:12:43] arathorn

Indexed properties.

Currently, a (single) indexer can be defined for a class to access data by index, but index parameters cannot be added to individual properties. Something like this:

class Foo
{
  public string this[int index] { get; set; } // indexer
  public string Bar[int index] { get; set; }  // indexed property -- unsupported
}

Foo f;
string a = f[0];     // use class indexer
string b = f.Bar[0]; // use indexed property -- unsupported

Managed C++ and C++/CLI both support indexed properties -- strange that C# does not. This MSDN page describes a somewhat-clumsy workaround for C#: http://msdn.microsoft.com/en-us/library/aa288464(VS.71).aspx [1]

[1] http://msdn.microsoft.com/en-us/library/aa288464%28VS.71%29.aspx

what's an indexed property? - RCIX
I updated the answer description. - arathorn
43
[+2] [2009-10-04 12:01:59] gkdm

It is often (rightfully) noted that interfaces are not contracts [1], and constrain nothing but class semantics, not behavior. How about "Contracts" being a combination Of .NET 4.0 CodeContracts Pre And Post Conditions and interface like signature definitions providing for true contracts and truly verifiable code in .NET.

public Contract IList<T>
{
    Add(T item)
    {
       // Pre and Post Conditions
    }

    int Count {get;}
}
[1] http://blogs.msdn.com/kcwalina/archive/2004/10/24/246947.aspx

44
[+2] [2008-10-26 15:46:03] leppie

How about something like anonymous interfaces?

Example:

interface IFoo
{
  int Bar {get;set;}
}

IFoo foo = new IFoo { Bar = 1 };

I'll just move to F#: codebetter.com/blogs/matthew.podwysocki/archive/2008/11/26/… - Mauricio Scheffer
This would be nice, however we would have to be careful that the syntax doesn't make it appear as though interfaces themselves are instantiate-able. Maybe some type of "as" keyword used after the type would be more effective, especially for supporting multiple interfaces. new { Bar = 1 } as IFoo, ISomeOtherInterface or maybe a : new { Bar = 1 } : IFoo, ISomeOtherInterface - jpierson
45
[+2] [2008-10-31 13:27:07] Kibbee

Inline regular expressions, like in Perl/javascript. I really like using regular expression, but sometimes it seems a bit excessive to set up a bunch of objects just to do a simple REGEX replace.


46
[+2] [2008-11-04 00:21:21] Chris Thompson

Easier event handling.

VB has had RaiseEvent and Handles, but C# has no equivalent.

C# should have a RaiseEvent keyword that takes care of all of the issues that people have with C# events, like null checking, thread safety (adding/removing handlers while being raised), etc.

Along with Events, I'd like to see Asynchronous events where you can raise an event that's more like a notification ("Hey, BTW, this just happened") but code can continue to execute without waiting for the listeners to finish executing.


47
[+2] [2008-11-04 00:30:54] Orion Edwards

I would love to see Implicit Interfaces

For example, If I had

public interface IFooable{
    string FooIt();
}

Then any class which implemented a function string FooIt() should automatically be an acceptable IFoo, regardless of whether the class builder had remembered to write class MyClass : IFoo in it's class declaration.

The compiler should be able to infer this, and produce appropriate MSIL while staying completely within the bounds of static typing and without reflection


I've wanted this for a while, specifically because of the way it would enhance generics. The constraint "where T : IFooable" would now just mean that T should implement a suitable FooIt(), i.e. it would allow C++ style static duck typing. - Daniel Earwicker
Dynamic typing FTW :) - orip
This is called "generalized interfaces", see blogs.msdn.com/ralflammel/archive/2006/12/23/… - Mauricio Scheffer
@orip: it can be done in static, strongly typed languages. - Mauricio Scheffer
This seems like longhand for delegates... - leppie
delegates? what have interfaces got to do with delegates? - Orion Edwards
(2) I think this is a very bad idea. It implies that the name of a method defines its purpose and semantics. Should List.Clear() and Window.Clear() be assumed to mean the same thing to the interface IClearable { void Clear(); }? - LBushkin
Yes, I'd LOVE it if IClearable worked like that. - Orion Edwards
This does not seem like a good idea to me. Even don't want to know problems which may raise. - Arnis L.
I can see difficulties with performance when requiring checks on all parameters passed to any method that accepts a particular interface type. The complier wouldn't be able to help in cases where assemblies are loaded dynamically which contain conforming types, so the checks would have to exist for each parameter and in each case it would be a reflection type introspection would would mean horrible things for performance. Now once a type is considered compatible that fact could be cached but still this would require a look up for each call to a method with that interface parameter. - jpierson
48
[+2] [2009-02-05 18:49:41] Joel Coehoorn

Multiple/generic setters for properties:

private Uri _linkUrl;
public Uri linkUrl
{
    get { return _linkUrl; }
    set
    {
        _linkUrl = value;
    }
    set<string>
    {
       _linkUrl = new Uri(value);
    }
}

//this of course works fine
MyObj.linkUrl = new Uri("http://stackoverflow.com"); 

// but I could also just do this:
MyObj.linkUrl = "http://stackoverflow.com";

Also see the discussion with this other question. [1]

[1] http://stackoverflow.com/questions/516981/what-features-do-you-wish-were-part-of-c/517040#517040

(2) I believe the same result can be achieved by having an implicit overload operator on the Uri class, for instance. - eulerfx
49
[+2] [2009-05-02 01:38:17] Dev

I wish there was something similar to the 'in' keyword in SQL, so instead of writing:

if (myobject.MyProperty == MyEnum.Value1 || myobject.MyProperty == MyEnum.Value2)
{
    // do something
}

I can write:

if (myobject.MyProperty in (MyEnum.Value1, MyEnum.Value2))
{
    // do something
}

you can do this with linq and extension methods it will be a method instead of a keyword but it makes it possible today - Matthew Whited
I know it's possible with a method but with the keyword it looks a lot better and more readable - Dev
* Use Delphi:) - tuinstoel
As in python... :) if x in ['a', 'b']: dostuff() - Macke
50
[+2] [2009-05-18 14:35:16] community_owned

I would like to see nested enums, so that such things will be possible:

var Region = Universum.Milkstreet.SolarSystem.Earth.Euroope.Germany;

Today we use nested structs for such things, but it is not type safe.


51
[+1] [2009-05-18 14:41:46] ilivewithian

How about internalised ultra private properties:

The syntax would like a bit like this:

public string MyName
{
   string _myName;
   get
   {
      if(_myName == null) _myname = string.empty;
   }
   set;
}

The idea is that the property can have state and apply rules to it's value, but nothing else in the class can access the real value underneath.


52
[+1] [2009-05-20 09:15:14] DavidWhitney

Method interception.

Support for custom code on method boundaries would enable us to do the kind of stuff PostSharp is good at, without having an extra tool to post-process the IL.


53
[+1] [2009-05-11 15:03:44] Steve

A with statement. The .NET framework is great but you end up with alot of long message chains due to the object nature of the framework. Code like this:

int x = myobject.mychild.myppoint.X;

If we had a with...

with(myobject.mychild.mypoint)
{
  int x = X;
}

I like it but I think the "X" should be ".X" similar to the construct in VB... also helping make the scope of the member more obvious - Matthew Whited
(2) Why? you can always create a one-letter temporary variable, and it won't cost you much typing. - erikkallen
54
[+1] [2009-02-24 00:20:39] Paul Stovell

When an object implements multiple interfaces, and I want to expose both, I'd like to return it in one go. E.g.,:

public {IEnumerable<T>, INotifyCollectionChanged} GetItems()
{
    return new ObservableCollection<T>();
}

var items = GetItems();

Secondly, I'd like the ability to return anonymous types from a method:

public var GetStuff()
{
    return new { Name = "Paul" };
}

There's no reason the compiler couldn't turn that into:

public <>_AnonymousObject923938 GetStuff() ....

As it does with all anonymous type usage.

Lastly, generic type parameter inference works with method calls, but not with constructors, when it should. This should just work:

var kvp = new KeyValuePair(8, "Hello") // KeyValuePair<int, string>

Your first suggestion sounds good, but there is an easy way to achieve the same, by defining another interface inheriting from both :) - leppie
yes, but then you need to change your concrete types to implement your custom interface. and if you didn't write the concrete types, you end up writing adapters, which isn't much fun - Paul Stovell
55
[+1] [2009-02-24 00:24:46] Paul Stovell

Anonymous types should be interfaces instead of sealed classes. It should then be up to the LINQ provider to generate the type as it sees fit.

Then when you do a projection with my LINQ library, I could return an object implementing INotifyPropertyChanged.


I had an idea along the lines of anonymous interfaces, although limited, it should not disturb the language in any way. - leppie
56
[+1] [2009-04-15 19:36:11] Chris S

1

I'd like an inbuilt Exception constructor that takes a string formatter like params object[] for a message.

throw new Exception("Your {0} blew up when opening {1}","Custard.Factory",filename);

2

This is a .NET feature request rather than C#. I'd like to see a DateTime formatting string option that adds 'st,nd,rd' to an English date. They're very easy to write but it means you can't just use the default formatting. e.g.

1st April
2nd February


57
[+1] [2009-01-21 10:29:49] Steve Dunn

const parameters and const methods ala C++ (http://stevedunns.blogspot.com/2008/11/c-4-default-parameters.html).

Also, extension properties. The comments on this request above stated that for extension properties to work they'd have to be readonly. const-ness would ensure this.


58
[+1] [2009-01-09 13:58:27] peSHIr
[1] https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=282003
[2] https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=253384

59
[+1] [2008-10-29 17:40:37] Judah Himango

I want language features that help us write less buggy code.

As others have noted, Spec# (a C# superset research language at Microsoft) has accomplished this by integrating design-by-contract, immutability, pure functions, and non-null types into the language.

Anders, Lippert, C# team: It's high time Spec# gets rolled into C#. It will help us write code with fewer bugs. That's something every developer can get behind.


Also notice that the .NET framework developers seem to be using Spec# to some extent. Look at Microsoft.Contracts.Contract class (internal) inside System.Core.dll. - Judah Himango
(1) Some aspects of Spec# are making it in to .NET 4.0 with the CodeContract static class. Looking at Microsoft.Contracts.Contract, it's very close to what will be in the CodeContract class. - Scott Dorman
Yeah, after watching some more PDC videos, I see the CodeContracts class (to be renamed Contracts later). Cool. - Judah Himango
60
[+1] [2008-11-21 10:04:53] Keith

Fascinating talk by Anders at the PDC:

http://mschnlnine.vo.llnwd.net/d1/pdc08/WMV-HQ/TL16.wmv

It looks like C#4 will support:

  • More parallelism
  • dynamic types with the new "dynamic" keyword
  • optional and named parameters - easy interop in C# at last!
  • co & contra variance on generics
  • better compiler control for dynamic code execution

61
[+1] [2008-10-21 17:56:49] Mark Cidade

I put in a feature request for ruby-style blocks [1].

[1] https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=369334

lambda's and anonymous functions do the same sort of thing, enclosures that can use local variables of where they are declared and be passed around as objects :) - Sekhat
it's a syntax thing--you can't pass a lambda into a function without a closing round parenthesis after a curly bracket and often between semicolons, as in foo(x => { doSomethingWith(x); bar(x) ;}); - Mark Cidade
Do we really need another way to specify anonymous methods? - Judah Himango
Yes we do, if we want syntactic support for common usage scenarios. The anonymous method is completely abstracted from the code in this case. - Mark Cidade
62
[+1] [2008-10-21 18:36:48] Gary Willoughby

How about adding nothing?

Lets have a period where we can actually learn to fully use the tools we have then we can have a meeting to agree on what we need.


Upvote. C# has always been the strongly-typed language... - Jonathan C Dickinson
What MS needs to IMHO is create a CLR mode for Ruby, in that it doesn't seek to be backward compatible with vanilla Ruby (I.e. Ruby#) and leave C# as a strongly-typed language. - Jonathan C Dickinson
63
[+1] [2008-10-21 18:37:12] John Sheehan

I would like a short-circuited version of &=

So this:

bool isValid = true;
isValid = isValid && (obj != null);
isValid = isValid && (obj.IsLoaded);

Could be come this:

bool isValid = true;
isValid &&= (obj != null);
isValid &&= (obj.IsLoaded);

You can already perform &=, try it. Unless of course you are asking for a way to evaluate conditional and operations where if (in this case) isValid is already true then nothing else will be evaluated. Nevertheless, msdn.microsoft.com/en-us/library/e669ax02(VS.80).aspx - nyxtom
&= is not short circuited, so if I used &= line 3 of second example would throw a null object reference exception. in the first example, line 3 gets false on the isValid before the && operator, so it doesn't eval the second expression. - John Sheehan
Even with a &&= operator, your code would still throw a NRE. The second LOC couldn't keep the third LOC from executing. If that behavior were exceptable, where would it stop? Anyway, is there something wrong with "bool isValid = obj != null && obj.IsLoaded;"? - P Daddy
(1) No, it wouldn't. In the first example on Line 3, if IsValid==false, the second part isn't evaluated, that's what short circuiting is. So if &&= existed and was shortcircuited, it would evaluate itself first and only the part after the operator if self was true. - John Sheehan
The reason I want this is for readability. I don't like long if statements - John Sheehan
Gotcha. Short-circuit happens before right-hand side is evaluated. Makes sense. Still, for readability's sake, wouldn't "bool isValid = \r\n\tobj != null &&\r\n\tobj.IsLoaded;" work just as well? (Can't format here in comments, so excuse the "\r\n\t" formatting.) - P Daddy
bool isValid = obj != null ? false : obj.IsLoaded; - Matthew Whited
Which covers two cases. How about 5, 10, 20? - John Sheehan
64
[+1] [2010-07-16 17:36:42] Chris Marisic

I hate responding to these questions that have pages of answers since they just get washed away by the volume of it but regardless

What I would like to see is what I would describe as Extension Events.

The premise would be that all methods would expose events for method entry, method exit and method error. You would then be able to apply AOP to any class in an extremely trivial manner. And then for these events to have EventArgs that expose the incoming parameters and return results to allow interception of these for inspection or mutation.

There would be a special case for seal classes. Any class that is marked sealed would by pass raising the event notifications for the Extension Events so that it would eliminate being able to find the return licensed = false output to be set to true. This could also be easily handled with an Attribute to do the same thing and not require sealed, perhaps just make sealed classes automatically compile with the ignore extension events attribute.


65
[+1] [2010-03-20 21:24:01] Eric Lloyd

This was touched on above, but apparently, those that responded didn't get it, and I don't yet seem to have the points here to respond to the original post. So here goes:

I'd like to have an implicit (or at least enforceable) TSelf type for generic classes. Consider:

public class GenericWithFactory<TSelf, T> {
    public static TSelf Create(T parameter) {
        TSelf ret = default(TSelf);
        // initialize the object...
        return ret;
    }
}

Currently, in order to support a whole host of instance-type constructs, such as a factory method (Create(T parameter) in this case), you have to pass the class you're declaring as a type parameter:

public class GwfOfSomething : GenericWithFactory<GwfOfSomething, Something> {
    // ...
}

You're thus forced to repeat the name of your instance class before you've even got to the opening brace! Also, there's no sure-fire way to enforce that TSelf must always be the class that's being declared. Thus, you can't reliably stop the user from doing this:

public class GwfOfSomethingElse : GenericWithFactory<GwfOfSomething, SomethingElse> {
    // ...
}

So, from the base class, how do we generically access the type of the instance class? Syntactically, the cleanest approach would be to overload this, using it in a specialized where clause in the base class declaration:

public class GenericWithFactory<TSelf, T>
    where TSelf: this
{ /* ... */ }

Since the instance declaration can thus only ever have one value for TSelf, it can simply be elided in practice:

public class GwfOfSomething: GenericWithFactory<Something> {
    // ...
}

Whether this last is a good idea, and whether the actual TSelf type parameter is available in the subclass' scope is a subject for further debate. But at least we have a cleaner way of keeping track of instance types from generic bases.


66
[+1] [2009-05-25 02:50:36] LBushkin

Generic type partial specialization.


67
[+1] [2009-07-31 11:09:33] Groky

It would be nice to be able to declare arrays on the fly similar to javascript:

foreach (int i in [1,4,7,9]) { ... }

I'm not sure how this would work when the array items were of different types. C# could limit the items to being of the same type, or could use the most derived type common to each of the items, boxing if necessary.


(2) You could use this syntax : foreach (int i in new []{1,4,7,9}) { } - Romain Verdier
68
[0] [2009-09-23 19:34:46] Danny Varod

Primative/Struct template unsafe methods.

Example:

private unsafe ModifyStream<T>(byte[] stream) where T : primative/struct
{
    fixed (T* ptr = stream)
    {
        ...
    }
}

69
[0] [2009-09-26 14:37:02] MiffTheFox

I don't really know the term for this, but I want to be able to do something like this:

static void Main(string[] args){
    string text = args[0] orelse "Hello, world!";
    Console.WriteLine(text);
}

which would be equivialant to this:

static void Main(string[] args){
    string text;
    try {
        text = args[0];
    } catch {
        text = "Hello, world!";
    }
    Console.WriteLine(text);
}

Becuase I've always wished I could apply the ?? operator to arrays, but I can't because going beyond the upper bound in the indexer throws an exception instead of returning null.


70
[0] [2009-06-29 15:57:18] peterchen

I want enums that don't need to be qualified by Namespace.EnumName when it is clear from the context:

enum E { a, b, c }; 
void Foo(E value) { ... }
void Bar() 
{ 
  Foo(a | b); 
}

That could improve readability of calls to functions like

double Regravitate(string name, double height, bool metric)

double x = Regravitate("kfo", 23.7, true);

to

double x = Regravitate("kfo", 23.7, metric);

71
[0] [2009-05-25 04:38:30] Pat

An in-built BIG number type. Or at least something bigger than long (Int64).

Something like Microsoft.Scripting.Math.BigInteger is working for me at the moment (lifted from IronRuby), but I'd LOVE to see something like this built-in!


You got your wish - System.Numerics.BigInteger is in Net 4.0 - blogs.microsoft.co.il/blogs/pavely/archive/2009/05/26/… - Dan Diplo
Awesome, thank you so much! Now it's one LESS library I need to go hunting down to do Euler problems :) - Pat
72
[0] [2009-05-25 04:45:35] Richard Hein

The ability to declare generics contraints based on methods or properties that the type must implement, without using an interface. I guess that would require duck typing.

Edit: Someone is going to say, "you'll be able to do that with dynamic types", and yes I agree, although the syntax isn't what I was thinking of, it will allow this to work.

Or, alternatively, and almost as useful, the ability to have a where constraint that allows you to specify that a T is one of a set of possible types:

void Foo(T foo) where T : Bar | IFoo, new() { foo.SomeMethodOnIFooAndBar(); }

This wouldn't be a small change. It would take a lot of changes to the CLR and compilers to be able to say that a object can be one out of a set of multiple types. Not to mention the changes required to make intellisense work.


73
[0] [2009-06-27 06:02:28] RCIX

Something to let me use all of the sub-namespaces in a namespace, ideally something like this:

using System.*;

(2) If you had that for a namespace I made you would regret it. - Joshua
74
[0] [2009-06-27 06:07:14] RCIX

Not particularly of interest, but it would be nice to go

Foo foo = new(bar, "baz");

And how would the compiler know what to emit if you have available to you a Foo object and any number of descendants? - jasonh
(1) If that is the case then it has no choice to assume you are trying to make exactly what you tell it. (as in, if you tell it Foo and Foo has descendants then it woul make a foo. - RCIX
75
[0] [2009-10-27 14:29:48] Simon

One thing I've wanted recently is a quick way of doing multiple case statements, esp. in state machine transitions. It would be nice to be able to write:

switch (oldState, newState)
{
    case 0, 1:
        // code for the 0 -> 1 transition;
        break;

    case 0, 2:
        // code for the 0 -> 2 transition;
        break;

    case 0, default:
        // code for other transitions from state 0;
        break;

    case 1, 3:
        // code for the 1 -> 3 transition;
        break;

    case default, 3:
        // code for other transitions to state 3;
        break;

    case default, default:
        // code all for other transitions;
        break;
}

as a shorthand for

switch (oldState)
{
    case 0:
        switch (newState)
        {
            case 1:
                // code for the 0 -> 1 transition;
                break;

            case 2:
                // code for the 0 -> 1 transition;
                break;

            default:
                // code for other transitions from state 0;
                break;
        }
        break;

    case 1:
        switch (newState)
        {
            case 3:
                // code for the 1 -> 3 transition;
                break;

            default:
                // code all for other transitions;
                break;
        }
        break;

    default:
        switch (newState)
        {
            case 3:
                // code for other transitions to state 3;
                break;

            default:
                // code all for other transitions;
                break;
        }
        break;
    }
}

notice that the code run in case default, default occurs in two places in the second example. This is a trivial example and already you get a 50% reduction in code length with hardly any lack of clarity - though you do have to bear in mind that order matters so case 0, default beats case default, 3.


and, yes, I know this is a bit late. C# 4.5, maybe? - Simon
76
[0] [2010-03-08 07:49:07] Eon

I'm fairly new in C#; maybe there are easy solutions for my problems but I've hit a couple of annoyances.

It's too late now but I would like to be able to add extension methods to static classes, like adding a Math.Sqr() or Math.DegToRad() function to use but two examples. Currently the logically named Math class is monopolized by a very sparse implementation of functions and I can think of lots of things I would want to add here. Sure, I could create something like MathEx but I would like to use the logical keyword Math.

On a related note, I would like a way to leave out the class name like Math. every time I type a function. Something like Delphi's "with" statement (with Math do { }).

The recommendation by ILoveFortran about adding an IArithmetic interface made above is also a brilliant one. Especially considering how a popular use for templates/generics is having a generic type that can use single or double precision floats.


77
[0] [2008-10-21 18:27:54] Victor Rodrigues

Improvements for LINQ: a more intuitive support for ORM and CRUD in general, like in Ruby on Rails, and not only for SQL Server, also for other databases.


not even MS wants to tackle the OrclBeast. I'm no dummy and that stuff is ridiculously over complicated. - StingyJack
78
[0] [2008-10-21 17:17:38] Victor Rodrigues

Would be interesting if I could do, inside the context of Dynamic Lookup (a feature to come with C#4), something like that:

dynamic
{
   object dynamicObject = GetDynamicObject();
   string method = "Foo"; /* or a call to somewhere in order to initialize this string */
   dynamicObject.method(); /* in this case, it means 'dynamicObject.Foo();' */
}

The goal of DLR is to ease the way we use reflection in C#. Since this construct can't compile in normal C# (object.stringIdentifier() ?), could inside a C# 4 dynamic block do this to improve reflection usability.

I know that according to the definition I saw on this article [1], this should call a method named 'method'. But when there is an identifier on the block with this name, could be more interesting to the developer to use this information. This identifier could refer basically to a string, but pottentially to other objects with more method info.

[1] http://blogs.msdn.com/charlie/archive/2008/01/25/future-focus.aspx

79
[0] [2008-09-26 09:15:35] Jesper Blad Jensen aka. Deldy

A ReadMyMindAndBuildApplication() method - that could be neat.

Or XML Literals like in VB.NET.


Why XML literals? I can see their use in VBA, but for most purposes it seems that cause confusion between code and data. - Keith
Keith: Code is data. - TraumaPony
I've had clients who called that method more than a few times. - Gthompson83
(1) Nah, code is logic, data is stored information. While there is some overlap (constants, code resources) for the most part you want to keep data out of code. - Keith
Although XML literals is very good for code generation, and a bunch of other stuff. But thanks for downvoting me, it was a valid wish, but people just like to downvote what they dont like, instead of downvoting what is a bad answer. - Jesper Blad Jensen aka. Deldy
I don't think people are downvoting XML Literals, but rather the slightly humerous precursor in your answer. If you edited that out, I'd upvote your answer in the blink of an eye. XML literals in C#4.0, pleeeeease! ;-) - Rob
... its called Python :-) - Johannes
I don't think it was worth a downvote, so I've nullified it. :D XML Literals, although not particularly useful to me, might not be bad per se in C#. Most of the arguments against it appear very similar to the arguments against LINQ, and LINQ just plain rocks! - Randolpho
80
[0] [2008-09-26 11:06:53] Mark Heath

I would like to be able to cast between arrays of unmanaged types [1] without the need for unsafe code and fixed pointers. There are some hacks that you can use to do this (explicit layout structs), but language support would be great.

float[] floatArray = (float[]) byteArray;
[1] http://mark-dot-net.blogspot.com/2008/05/wanted-language-feature-reinterpret.html

What's wrong with using unsafe blocks here? The operation is unsafe, so this is actually the only viable solution. - Konrad Rudolph
the issue is to use the unsafe route you need to pin the memory which causes performance problems. Also, there is nothing inherently unsafe about this so long as you don't go over the end of your array (which there is already checking built in) - Mark Heath
Unsafe casts are unsafe. No. - IDisposable
81
[0] [2008-11-25 17:07:50] Simon

I'd like to be able to make private variables local to a region, so that I can force myself to use accessors. Like this:

#region MyValue

private int myValueSets = 0;

[RegionLocal("MyValue")]
private int myValue = 0;
public int MyValue
{
    get { return myValue; }
    set { myValue = value; myValueSets++; }
}

#endregion

public void doStuff()
{
    // this is OK
    int i = MyValue;

    // so is this
    int j = myValueSets;

    // but this is a compile-time error
    int k = myValue;
}

Since it's just there as a warning to the compiler, it wouldn't require any changes to the MSIL.

Oh, and another vote for string enums, please. Maybe other structures could be enumerated - Color enums would be handy.

UPDATE: Mike Hofer points out that regions don't mean anything to the compiler, so as an alternative way of achieving the same thing, how about allowing variables to be scoped like this?

public int MyValue
{
    int myValue = 0;

    get { return myValue; }
    set { myValue = value; myValueSets++; }
}

The problem with this is that regions don't mean anything to the compiler. Their original intent was to hide generated code so you didn't have to look at it. If you want to properly scope the variables, put them in a real type, or redesign properties so that fields are local to them. - Mike Hofer
Interesting idea. I can see it being useful, but I also think that 9 times out of 10 if you want to do this you probably need to break that code out into it's own class. - Joel Coehoorn
82
[0] [2008-11-12 17:04:21] Scott Dorman

All of these posts have been what people wanted to see in C# 4.0. Now that it has actually been announced, we can safely say that the following features will be part of C# 4.0:

  • dynamic dispatching (with a new dynamic keyword)
  • named and optional paramters
  • contravariance and covariance (through in and out keywords)
  • Tuples
  • BigInteger

There is more, but this covers most of the features that people were asking for that will be in the next release.


83
[0] [2008-11-06 23:04:50] dswatik

I would want optional parameters like in VB so I wouldn't have to write overloads

example

public string GetPath(string root, optional string subroot)
{
   return root + subroot;
}

Optional parameters will be in the CLR. - Scott Dorman
84
[0] [2008-10-31 12:39:51] Stimul8d

I'd like a 'Singleton' accessor so i could define as class a la 'public singleton class'. I have a generic one i use most of the time but the syntax bugs me. It's a common pattern so why not?


Singletons are evil except for very special cases: google.com/search?q=singleton+evil - Mauricio Scheffer
(1) I wouldn't say they/re evil, just that they may be able to be replaced by a well-written set of static methods in some cases. - RCIX
thanks for the pragmatism RCIX. - Stimul8d
85
[0] [2008-10-31 13:23:50] adam straughan

Infered interface casting (sort of Duck typing), performed at runtime

See code below. Anything that logically implements and interface without explicitly doing so could be inferred into an interface.

At runtime the compiler can generate a runtime adapter around whatever is passed in or if the cast cannot be completed either throw a cast or inferred cast exception or, as with 'as,' return null.

This would allow less code to be written and allow built in type or types from 3rd Party libraries to be used in a testable fashion.

class Button { public string Text {get; set; } public void Other(){} }

class CustomerLabel { public string Text {get; set; } public Size Width {get; set; } }

interface IHasText { string Text{ get; set;} }

// some other method public void TextDecorator(IHasText item){}

// in use var b = new Button(); TextDecorator(b infer IHasText);

adam


86
[0] [2008-10-29 08:18:51] community_owned

I'd like to see a attribute to type methods that update GUI as threadsafe.

Now we add delegates for all methods called from worker threads that update the gui followed by the pattern if (this.InvokeRequired) then create and invoke delegate (new object {bla}).

To be more productive, something like

[GUISafe] void Foo(int percent) { progressbar.value = percent; }

void WorkerThread() { Foo(15); }

would help a lot.


87
[0] [2009-01-20 09:06:53] Click Ok

I want direct access to low level system APIs and never don't "to dirty the hands" with c++ :-)


88
[0] [2009-01-02 18:32:25] Walt D

Methods that must be private and can only be called from constructors and other such methods, but can modify readonly fields.


What about using a private constructor? - Mauricio Scheffer
89
[0] [2009-02-05 18:36:48] Joel Coehoorn

The ability to map a class to an interface implementation outside the class definition.

For example, let's say you're building a file archiving/encryption utility, and you want to build on SharpZipLib. You also have a separate PGP implementation. It would be nice to be able to map the base SharpZipLib interface and the separate PGP code onto a common interface that can youc can use in the rest of code without caring which is which.

Another example would be mapping System.Xml.Serialization.XmlSerializer to implement System.Runtime.Serialization.IFormatter.

I have no idea what the syntax would look like (perhaps similar to extension methods?), but I'd love to see it made possible.


90
[0] [2009-02-16 05:05:46] ebattulga

If I need to change open dialog, like this

public class MyDialog : OpenFileDialog
{
   ...// change some user interface on designer
}

public static void Main()
{
    OpenFileDialog.DefaultForm=new MyDialog(); // Every Dialog has a DefaultForm property
    //MessageBox.DefaultForm, SaveFileDialog.DefaultForm, ColorDialog.DefaultForm etc.
}

and using like this

void MyFunc()
{
   OpenFileDialog od=new OpenFileDialog(); // 
   od.ShowDialog();// MyDialog shown
}

91
[0] [2009-04-23 16:55:15] Victor Rodrigues

I wish I had this possibility of foreach use:

public static void GenerateReports(DateTime beginDate, DateTime endDate)
{
    foreach(DateTime date between beginDate and endDate)
    {
       GenerateReport(date);
    }
}

you could write an extension method to hang off DateTime objects to be called like startDate.ToRange(endDate) and have it return an IEnumerable<DateTime>() - Matthew Whited
(1) True, but it's not quite the same. C# needs more "fluent language" keywords in my opinion. - RCIX
You want a report for every distinct datetime (to the millisecond!) between two dates? Also, why not just make it a for-loop? You're not iterating over a collection, you're iterating over a range. - Blorgbeard
You'd need some kind of step keyword for this and a sensible default if not provided (so for dates it would days and not milliseconds) - Dan Diplo
92
[-1] [2009-03-27 15:44:24] Gidon

Being able to enlargen the scope of a getter/setter on a derived class:

public class ReadOnlySomeClass {

   internal ReadOnlyClass(int myProp)
   {
       this.MyProp = myProp;
   }

   public virtual int MyProp { get; protected set; }

}

public class SomeClass : ReadOnlySomeClass {

    internal SomeClass(int myProp) : base(myProp) {}

    public override int MyProp {
       get { return base.MyProp; }
       set { base.MyProp = value; } // is now public.
    }
}

(1) this would break the encapsulation principle. - Victor Rodrigues
93
[-3] [2008-09-26 14:15:50] spoulson

At times I've wished I had a ?= down-cast operator, like in ABAP, to ease the wordiness of explicit type casting. I'm sure there's a reason it doesn't already exist, but I'm throwing it out as food for thought.

// implicit up-cast
Base object = new Derived();

// explicit down-cast
SomeClass foo = (SomeClass)bar;
// or
SomeClass foo = bar as SomeClass;

// implicit down-cast operator concept
Base bar = new Derived();
Derived foo ?= bar;

The condition for ?= is that the two types must be related. The outcome is just shorthand for using the (Type) type cast operator without explicitly specifying the type. This has the added benefit of compiletime type compatibility:

// Runtime error
UnrelatedClass baz = new UnrelatedClass();
Derived foo = (Derived)baz;

// Compiletime error
UnrelatedClass baz = new UnrelatedClass();
Derived foo ?= baz;   // baz's type has no relation to foo's type

"(SomeClass)bar" and "bar as SomeClass" do different things, which would you expect ?= to do? - Keith
I think he is trying some alchemy :) - leppie
You might want to check out the casting operators in F# - Mauricio Scheffer
94