views:

12875

answers:

96

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 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. I hope we would be able to leverage, at some level, the underlying DLR mechanisms from C#-the-static-language.

What about you?

+113  A: 

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.

Matt Hamilton
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
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
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
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
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
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
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
Agree with Rick: it's cool, but doesn't demonstrate why extension properties would be valuable on a large scale.
peterchen
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
F# has this: http://codebetter.com/blogs/matthew.podwysocki/archive/2008/09/10/object-oriented-f-extension-everything.aspx
Mauricio Scheffer
It's amazing how F# does it and seems like they justified it, I mean extension everything, not just properties.
Joan Venge
"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
@BoltBait you have a strange definition of "ugly"! How is '2.Minutes.Ago' "uglier" than 'DateTime.Now.AddMinutes(-2)'???
Matt Hamilton
I'm still lost on why "var time = 2.Minutes().Ago();" is such a big problem.
Matthew Whited
"""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
"""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
2.Minutes.Ago looks like Ruby. (Not a problem, just saying.)
Sarah Vessels
@Kibbee totally missed the point.
Owen
Stop stealing from Rails...
Min
@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
+103  A: 

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.

Michael Stum
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
They made Auto-Properties just to reduce clutter, so they can as well make Optional Parameters for the same purpose :)
Michael Stum
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
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
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
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
+6  A: 

It's too late now but instead of LINQ 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.

Konrad Rudolph
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: http://langexplr.blogspot.com/2007/02/list-comprehensions-across-languages_18.htmlhttp://www.anexperimentinscotch.com/?p=450
Mauricio Scheffer
can you live a simple example (perhaps in python)
acidzombie24
A: 

A ReadMyMindAndBuildApplication() method - that could be neat.

Or XML Literals like in VB.NET.

Jesper Blad Jensen aka. Deldy
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
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. :DXML 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
+27  A: 

My candidate would have to be point 4 from the anastasiosyal.com reference, "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!

Rob
I tried to do a generic extension workaround for that: http://stackoverflow.com/questions/123088/possible-pitfalls-of-using-this-extension-method-based-shorthand
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
+48  A: 

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

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:

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

Keith
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
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
Marc Gravell
Thanks (interesting link), but that really isn't the same thing. Nice workaround though.
Keith
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
+78  A: 

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.

Matt Hamilton
That would be nice :)
leppie
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
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
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
@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
+33  A: 

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.

Adam Wright
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
I read your answer out loud to my coworkers, and they all laughed and agreed with you whole heartedly.
Joshua Carmody
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
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
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
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
@ 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
It seems to me that these arguments stem from a feeling of wanting "the best" all the time.
Matt Olenik
>> @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
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
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
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
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
+18  A: 

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.

morechilli
Why not just "using"?
Marc Gravell
Using can only be used for local scope - useless for member variables.Managed c++ copes well with IDisposable members.
morechilli
Agree 100% with this. http://incrediblejourneysintotheknown.blogspot.com/search/label/IDisposable
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 http://stevedunns.blogspot.com/2009/03/idisposable-alerts.html for more info.
Steve Dunn
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
+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
A: 

I would like to be able to cast between arrays of unmanaged types 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;
Mark Heath
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
A: 
  • Interfaces that include a class' static members.
  • Option to allow sub-classes to inherit attributes from their parents.
  • Generic constrains based on value types.
  • Multiple Inheritence the Eiffel way.
Kramii
I don't mind being voted down (that's the point of SO) but it would help me if you could say *why*. Thanks.
Kramii
Not one of the voters, buuut, sub-classes do inherit attributes, according to the AttributeUsageAttribute declaration on the Attribute implementation (and correct resolution).
Jonathan C Dickinson
Jonathan:Thanks so much for your comment. I really appreciate that you took time to critique my suggestions, and I've learned something important I didn't know.
Kramii
Interfaces can't have static members for very practical reasons. No implementation is attached to an interface. The nature of an interface is to defer to an _instance_ of a class to do the work. Static methods by nature are _not_ associated with an instance. They're mutually exclusive concepts.
Chris Ammerman
Turbulent Intellect: Thanks for the comment, but I'm not (yet) convinced. In order to promote discussion (and my learning) I've asked a question on this topic:http://stackoverflow.com/questions/259026/why-doesnt-c-allow-static-methods-to-implement-an-interface
Kramii
+7  A: 

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. 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.

Chris Ballard
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
+91  A: 

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.

Jon Skeet
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
+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
@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
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
+19  A: 

Named parameters

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

GvS
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
+13  A: 

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);
SeeR
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
+63  A: 

Auto implemented property initializers.

public List<string> MyList { get; set; } = new List<string>();
Torbjörn Hansson
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
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
I dont understand this. Why wouldnt you use public List<string> MyList = new List<string>(); instead
acidzombie24
@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
+20  A: 

I'm a nostalgist:

System.Error.BlueScreenOfDeath.Appear();
Andre Bossard
Amusing........
John JJ Curtis
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
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
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
+55  A: 

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

Seriously, it's awesome.

TraumaPony
+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: http://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
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
The static analysis tool is only for Team Suite editions of Visual Studio, still glass half full and all that...
FinnNk
A: 

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
spoulson
"(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
+112  A: 

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"
      }
   }
}
Johan
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
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
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
Like Anthony, I cannot see the benefit. This seems like a foolish feature to add.
Judah Himango
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
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
Why not simply use a class with constants only?
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
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
+5  A: 

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)

Mauricio Scheffer
yes, I guess BlueScreenOfDeath.Appear is more helpful than this.
Mauricio Scheffer
+7  A: 
public static T CallWithCurrentContinuation<T>(Function<Continuation,T> cc);
leppie
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
+12  A: 

Given that everyone hits issues 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 and even suggests some syntax options (and asked people to vote for their favorite).

Hamish Smith
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
+35  A: 

To be able to write binary values:

int myInt = (int)%00011011 | (int)%11111110 | myOtherInt;
Torbjörn Hansson
Ooh. That's a fun concept!!!
Jonathan C Dickinson
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: http://fsharpdotnet.com/fsharp-literals/
Mauricio Scheffer
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
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
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
+6  A: 

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.

Quibblesome
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
Seriously, C# is rapidly turning into C++ with its everything _and_ the kitchen sink mentality. KISS!
David
+27  A: 

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.

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
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
+3  A: 

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;
   }
}
Jonathan C Dickinson
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
jpierson
+5  A: 

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.

Pop Catalin
IMO traits or mixins are a cleaner solution
Mauricio Scheffer
@mausch, not if you try to create monads ;)
Pop Catalin
A: 

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, 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.

Victor Rodrigues
+1  A: 

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

Mark Cidade
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
A: 

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.

Victor Rodrigues
not even MS wants to tackle the OrclBeast. I'm no dummy and that stuff is ridiculously over complicated.
StingyJack
+1  A: 

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.

Gary Willoughby
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
+1  A: 

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);
John Sheehan
nyxtom
John Sheehan
Even with a "?
P Daddy
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 " 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
+16  A: 

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.
Krzysztof Koźmic
#2, you're basically talking about an automatic backing store?
Joel Coehoorn
ILoveFortran
Sorry, that was the cached link; here is the real one:http://blogs.msdn.com/bclteam/archive/2008/11/11/introduction-to-code-contracts-melitta-andersen.aspx
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
+47  A: 

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 ;)
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
+2  A: 

How about something like anonymous interfaces?

Example:

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

IFoo foo = new IFoo { Bar = 1 };
leppie
I'll just move to F#: http://codebetter.com/blogs/matthew.podwysocki/archive/2008/11/26/object-oriented-f-encapsulation-with-object-expressions.aspx
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
A: 

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.

+22  A: 

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...
}
Chris Ammerman
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
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
+1  A: 

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.

Judah Himango
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
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
A: 

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?

Stimul8d
Singletons are evil except for very special cases: http://www.google.com/search?q=singleton+evil
Mauricio Scheffer
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
A: 

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

adam straughan
+2  A: 

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.

Kibbee
+2  A: 

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.

Chris Thompson
+2  A: 

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

Orion Edwards
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 http://blogs.msdn.com/ralflammel/archive/2006/12/23/generalized-vs-dynamic-interfaces.aspx
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
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
+39  A: 

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.

MrSlippers
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
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
A: 

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;
}
dswatik
Optional parameters will be in the CLR.
Scott Dorman
+3  A: 

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
A: 

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.

Scott Dorman
+3  A: 

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;
    }
}
Danny Varod
+4  A: 
Danny Varod
This can be done with F#: http://weblogs.asp.net/podwysocki/archive/2008/09/09/object-oriented-f-extension-everything.aspx
Mauricio Scheffer
Not sure about the syntax - "static this" is kind of an oxymoron..
Blorgbeard
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
+1  A: 

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
Keith
A: 

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++; }
}
Simon
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
+16  A: 

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

ILoveFortran
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
A: 

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

Walt D
What about using a private constructor?
Mauricio Scheffer
+9  A: 

Missing:

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

Nice to have:

  • AddRange support in read-only collection initializers
  • TThis pseudo-type in generic constraints (or even full JavaGI)
  • Some way of null-proof property traversal, like ?(a.B.C) returns null if a is null.
  • Shortcut syntax for IEnumerable<>
  • Object initializer support for factory method return values
  • Better forms of string.Format -- $"All ${userName} bases are belong to us".
Andrey Shchekin
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
RCIX
Andrey Shchekin
Upvote for generic attributes. Needed those recently. Other points ain't bad too. :)
Arnis L.
what do you mean by generic attributes?
acidzombie24
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
+1  A: 
peSHIr
A: 

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

Click Ok
+1  A: 

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.

Steve Dunn
A: 

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.

Joel Coehoorn
+2  A: 

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.

Joel Coehoorn
I believe the same result can be achieved by having an implicit overload operator on the Uri class, for instance.
eulerfx
A: 

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
}
ebattulga
+1  A: 

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>
Paul Stovell
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
+1  A: 

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.

Paul Stovell
I had an idea along the lines of anonymous interfaces, although limited, it should not disturb the language in any way.
leppie
A: 

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.
    }
}
Gidon
this would break the encapsulation principle.
Victor Rodrigues
+1  A: 

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

Chris S
A: 

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);
    }
}
Victor Rodrigues
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
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
+2  A: 

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
}
Waleed Eissa
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
Waleed Eissa
* Use Delphi:)
tuinstoel
As in python... :) if x in ['a', 'b']: dostuff()
Marcus Lindblom
+1  A: 

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;
}
Steve
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
Why? you can always create a one-letter temporary variable, and it won't cost you much typing.
erikkallen
+2  A: 

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.

+1  A: 

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.

ilivewithian
+1  A: 

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.

DavidWhitney
+3  A: 

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

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

Evan Moran
+2  A: 

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();
    }
}
LBushkin
+7  A: 

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;
}
LBushkin
+1  A: 

Generic type partial specialization.

LBushkin
A: 

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!

Pat
You got your wish - System.Numerics.BigInteger is in Net 4.0 - http://blogs.microsoft.co.il/blogs/pavely/archive/2009/05/26/biginteger-in-net-4-0.aspx
Dan Diplo
Awesome, thank you so much! Now it's one LESS library I need to go hunting down to do Euler problems :)
Pat
A: 

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.

Richard Hein
+18  A: 

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#.

Martin Konicek
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: http://dotnet.dzone.com/news/silverlightwpf-implementing
Martin Konicek
Thats called the infoof operator and it almost got in c# 4.http://blogs.msdn.com/ericlippert/archive/2009/05/21/in-foof-we-trust-a-dialogue.aspx
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
+3  A: 

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

Scala programming language supports this.

Martin Konicek
+1  A: 

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

arathorn
what's an indexed property?
RCIX
I updated the answer description.
arathorn
A: 

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

using System.*;
RCIX
If you had that for a namespace I made you would regret it.
Joshua
A: 

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

Foo foo = new(bar, "baz");
RCIX
And how would the compiler know what to emit if you have available to you a Foo object and any number of descendants?
jasonh
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
+3  A: 

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.

this. __curious_geek
excellent idea
acidzombie24
A: 

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);
peterchen
+1  A: 

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.

Groky
You could use this syntax : foreach (int i in new []{1,4,7,9}) { }
Romain Verdier
A: 

Primative/Struct template unsafe methods.

Example:

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

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();
Travis Heseman
that's crazy, I like it...
Steve
A: 

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.

MiffTheFox
+2  A: 

It is often (rightfully) noted that interfaces are not contracts, 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;}
}
gkdm
A: 

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.

Simon
and, yes, I know this is a bit late. C# 4.5, maybe?
Simon
+6  A: 

All events should be weak events 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.

Martin Konicek
A: 

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.

Eon
+1  A: 

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.

Eric Lloyd
+4  A: 

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", var value))
{
     ...
}

As opposed to the current calling code:

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

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

Reddog
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
+1  A: 

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.

Chris Marisic
A: 

For c#4.0 refer http://bimbim.in/post/2010/08/22/c-sharp-40-features.aspx

bimbim.in