114

Possible Duplicate:
C# Language Speculation 4.5 / 5.0

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

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

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

114

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

Tuple Packing and Unpacking

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

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

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

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

Do you mean something like this?

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

If so, I like it. Awesome idea.

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

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

is equivalent to

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

Meaning that syntaxes like

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

work as well.

104 accepted

An in keyword.

if (x in (1, 2, 3))
{ }
  • Like Python.
  • Without having to use extension methods.
95

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

string! nonNullable = someFunctionThatReturnsAString();

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

92

Extension properties.

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

var value = someObject.Value();

and

someObject.Value(newValue);

It seems I'm programming with Java.

92

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

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

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

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

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

Maybe even allow expressions that access members of the caseswitch:

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

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

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

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

83

Enum as a Generics constraint

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

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

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

73

Initial values for automatic properties

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

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

instead of having to create an explicit backing field:

private string _name = "(NA)";
public string Name
{
  get { return _name; }
  set { _name = value; }
}
55

Arithmetic type constraints:

public T Foo<T>(T blah) where T : number {
  return blah * blah;
}
45

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

Automatic Flag Enums

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

Example:

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

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

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

42

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

For instance I'd like to see

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

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

38

Enum classes (just like Java!)

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

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

Code example:

enum Direction {
   // This is the same as doing Right = new Direction(0,1), etc.
   Right(0, 1), Down(1, 0), Left(0, -1), Up(-1, 0);
   public int X { get; private set; }
   public int Y { get; private set; }
   // I has constructor!
   private Direction(int x, int y) {
      this.X = x;
      this.Y = y;
   }
   // I has methods!
   public Direction GetOpposite() {
       int opposite = this.Ordinal + 2;
       opposite = (opposite > Direction.Count) ? this.Ordinal - 2 : opposite;
       return Direction[opposite];
   }
}
38

Operator Constraints with Generics

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

Why not this:

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

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

Constructor Constraints with Generics

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

Expanded Support for Dynamic Typing

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

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

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

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

Currently, this would take:

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

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

Awful and painful.

JavaScript-style dynamic object literals

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

Instead of:

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

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

I would like to see:

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

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

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

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

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

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

So you need to do this:

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

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

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

Why not just:

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

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

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

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

Null Safe Member Operator

Instead of doing:

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

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

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

Easier Immutable Types

This is a hard one.

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

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

..

private Foo# _member;

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

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

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

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

Mono.Simd

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

Nested Iterators

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

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

By allowing me to write:

public override IEnumerable<int> Foo()
{
  yield return 1;
  yield return 2;
  yield return base.Foo();
}
32

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

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

32

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

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

You could use something like:

cake.?frosting.?berries.?loader

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

31

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

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

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

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


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

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

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


EDIT: moved the suggestion about indexed properties to another answer

29

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

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

Of course then we need pattern matching.

match (message)
{
    Get(id, channel):
    {
        // ...
    }
    Put(id, value):
    {
        // ...
    }
    Delete(id):
    {
        // ...
    }
}
28

"const" or "readonly" for local variables.

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

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

As in:

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

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

public void GetPixel(int x, int y)
{
    int offset = x;
    offset += (y * stride);    // Can still change it, as it's a writable variable
    ...
    freeze offset;             // 'offset' is now enforced read-only by the compiler
    ...
    offset *= 2;               // Error: This is read only
}
26

String Interpolation

These two lines of code...

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

Would be a lot nicer like this...

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

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

25

Language support for property change notification (INotifyPropertyChanged) :

public observable int Foo { get; set; }

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

24

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

public int SomeValue { get; readonly set; }

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

24

Remove C# attribute restrictions

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

[SomeCoolAttribute(s=>s.Foo)]
public string MyProp { get; set; }
22

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

For example, this is allowed, and gives null:

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

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

This, however throws a null ref exception:

class MyRefType { public string Value; }

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

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

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

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

IanG explains it in more detail, here:

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

22

First-class events

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

That way I could write

Observable.FromEvent(tree.MouseMove)

instead of

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

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

Observable.FromEvent<MouseEventArgs>(handler => tree.MouseMove += handler,
                                     handler => tree.MouseMove -= handler)
21

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

Enum Options : String
{
    Option1 = "xxx"
    Option2 = "yyy"
}
21
  1. A tool for converting old code to .Net 5, so Microsoft can fix a bunch of problems with the framework without breaking backwards compatibility (MS Connect)

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

19

Static extension methods

and

Static abstract methods

17

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

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

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

If an exception is thrown by the assigment

Prop2 = variable2.SomeMethod()

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

var someObject = new SomeObject()

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

17

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

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

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

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

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

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

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

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

17

Readonly automatic properties

So we could have something like:

public string Name { get; private readonly set; } 

or

public readonly string Name { get; private set; }

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

var p = new Person { Name = "Edgar" };
// p.Name is now immutable
14

The ability to handle long file paths in System.IO

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

13

yield enumerable

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

Current

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

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

  yield return feet;
}

Proposed

public IEnumerable GetAllMembers(MyObject obj)
{
  yield return obj.head;
  // BodyParts is IEnumerable, and we want to 
  yield enumerable obj.BodyParts;
  yield return feet;
}
12

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

12

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

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

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

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

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

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

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

11

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

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

Something along the lines of:

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

Which the compiler would expand to:

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

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

10

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

T Add<T>(T a, T b)
{
    return a + b;
}
10

Full support for Linux Platform. Mono is not happening.

9

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

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

You could shorthand it to something like

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

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

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

9

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

all this ControlCollection, XmlAttributeCollection, SqlErrorCollection

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

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

9

Same as for C# 4.0.

Missing:

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

Nice to have:

  • AddRange support in read-only collection initializers
  • TThis pseudo-type in generic constraints (or even full JavaGI)
  • Some way of null-proof property traversal, like ?(a.B.C) returns null if a is null.
  • Shortcut syntax for IEnumerable
  • Object initializer support for factory method return values
  • Better forms of string.Format -- $"All ${userName} bases are belong to us".
  • Additional LINQ operators for Take/Skip, Single and ToList/ToArray
  • Access to current item index in LINQ expression
  • Immutable types
  • Initialization for automatic properties
8

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

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

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

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

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

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

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

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

8

Interfaces / abstract classes for all .NET library concrete classes

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

Chained Comparisons

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

if we could do this, it would be nice:

bool isBetween = 20 < a < 30;
7

Arrays indexed by enums, Delphi style:

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

// Later..
mondayFun = dayFun[Weekdays.Monday];
7

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

7

Exception grouping to avoid duplicating the same handling logic

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

Multiple inheritance or a nice mixin implementation

public class A : B, C, ID
{
}

Switch done right without using break

switch (something)
{
    case 'A': ...
    case 'B': ...
}
7

Compile-Time Aspects

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

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

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

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

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

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

7

Allow T? for reference types

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

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

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

6

Initialization for automatic properties.

So instead of:

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

public string Text { get; set; }

we could have

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

or

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

or something to that effect.

5
  1. Creating an attribute that can only be applied to any class that derives from a given class.

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

  3. Extension properties.

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

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

5

Generic attributes...

5

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

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

And then from code-behind:

MyEnum value = DD.SelectedValue;

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

5

Direct delegates to property getters

See here

You can create a delegate directly to a method:

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

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

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

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

Func<int> func = get_IntProperty;
// or something like...
Func<int> func = &IntProperty;
4

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

For example:

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

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

public static bool VerifyXPath(string i_strXPath, bool i_bIncludeXPathPrefix)
{
    Log.Instance.MethodParameters();
    // etc.
}
4

Typedef keyword

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

edit:

@Drew:

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

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

4

Ability to write F# alongside C# code.

4

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

Something that would prevent:

public int Amount
{
    get { return Amount; }
}
4

Indexed properties, like in VB and COM :

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

    ...
    foo.Values[0] = "hello";
4

Something like this

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

    public abstract void Attack();
}

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

or

public void Main(string animalName) {
    Animals animal;

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

or maybe

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

Just like java

4

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

DelegateType? DelegateVar;

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

4

Static inner methods.

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

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

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

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

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

4

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

class Program {

   static void Main() {

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

output:

Program
String
Empty
Main

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

eg.

NorthwindContainer container = new NorthwindContainer();

var productsWithCategory = container.Products.Include(nameof(Product.Category));
3

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

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

On that note...

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

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

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

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

3

Anonymous Iterators

For example, so you could write something like:

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

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

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

3

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

3

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

3

Arithmetic operator overloading for generics

3

Interface operators or extension operators

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

interface INumericArray
{
    INumericArray MultiplyBy(INumericArray b);
}

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

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

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

2

An implied "new" type, so that

List<ListViewItem> listLVI = new;

means the same as

List<ListViewItem> listLVI = new List<ListViewItem>();
2

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

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

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

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


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

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

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

So we could do:

var c = new C();

c.MB1();

and so on.

2

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

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

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

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

2

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

Example:

if (foo) => if foo

DoIt(); => DoIt

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

Reverse if declaration

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

Instead of

if(foo) DoIt();

just

DoIt if foo

also this

DoIt unless foo
2

Virtual constructors and virtual static methods like in Delphi.

2

Support for Mixin's.

2

Ability to invoke static method on the generic parameter

public T Create<T>() where T : static Create()
{
     return T.Create();
}
2

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

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

public static void Extension(this UIElement e)
{
}

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

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

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

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

1

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

1

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

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

Basically:

interface IXyz {
   void someFunction();
}

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

interface IAbc {
   void otherFunction();
}

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

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

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

1

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

1

Native enum support in Linq to Entities:

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

1

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

1

Workflow designer controls?

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

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

Would make for interesting process design.

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

1

Derive from T:

class Foo<T> : T where T : class

Constraint for interfaces:

class Foo<T> where T : interface

And of course both together, implementing interface T.

1

Property notification for use specially in AOP.

1

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

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

1

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

1

Inline assembly language.

1

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

1

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

1

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

A new syntax would be required.

1

Roles

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

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

This is what Perl 6 and Moose call roles.

Unlike in Scala, roles would need explicit conflict resolution.

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

For example:

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

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

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

// ...

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

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

// ...

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

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

1

I would like to see a way to:

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

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

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

Example:

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

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

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

}

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

         [SettableBy(typeOf(Parent)]  // this specifies the "friend" class
         private set 
         { 
            _parent = value;
          } 
      }
  }
1

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

print "hello" If x = 0
1

Higher Order Generics (Generic Parameters with Generic Parameters)

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

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

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

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

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

0

Multiple Inheritance

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

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

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

0

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

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

0

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

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

0

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

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

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

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

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

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

0

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

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

0

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

For instance to have like

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

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

0

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

0

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

So

using System;

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

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

could be written as

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

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

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

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

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

0

Imm keyword

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

imm int x = 5;
x = 6; // error
0

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

IfNull and IfNotNull keywords

solves the "uglyness" of statements like

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

and the even worse

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

instead you'd be able to write:

IfNotNull(a,b)

and

IfNotNull(a.SomeProperty.SomeField) 

where it handles the shortcircuiting of the last example.

conditional return statement "return?"

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

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

with

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

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

Fire keyword for events

Resolves the verbosity of code like this

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

with

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

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

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

0

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

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

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

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

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

0

Braced switch syntax- (I like braces)

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

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

0

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

0

Automatic cast after 'is'

instead of:

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

it becomes:

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

and the compiler would emit code something like:

if(someObject is SomeLongAndAnnoyingClassName)
{
    var someObjectTemp = (SomeLongAndAnnoyingClassName)someObject; //see? var is useful!
    someObjectTemp.Name = "New Name";
}
0

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

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

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

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

0

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

Current:

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

Proposed:

List<Foo> foos = new List<Foo>();
foos orderby obj.Bar descending; //obj is a context-sensitive variable
//which translates into...
foos.OrderByDescending(obj => obj.Bar);
0

Allow in indexer of a foreach to be a ref

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

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

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

0

Possibility to declare local variables anywhere, e.g.

mydict.TryGetValue(key, out var value)

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

Some way to avoid code duplication in exceptions handlers

try {
    ...
}
catch (SomeException err) {
     // do something
}
catch (SomeOtherException err) {
     // do something else
}
catch continue {
     // do something common for all catched exceptions
}
finally {
     // always do something
}
0

Numeric literal suffixes for all numeric types

Currently the following suffixes exist :

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

For other numeric types, you have to cast explicitly :

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

I'd like to have the following suffixes added :

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

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

0

Structural constraints

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

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

Then I could use:

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

Or simple declare a variable of type MyConstraints:

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

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

-1

I would love to see that this is possible:

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

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

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

-2

Return type based Method Overloading

I know it's really difficult to handle this. But I really would like that method signature take method return type into account.

public string Foo()
{
     return ((MyType)Foo()).ToString();   // Will call MyType Foo()
}

public MyType Foo()
{
     return new MyType() { Prop="foo" };
}

string myString = Foo();                  // Will call string Foo()
MyType myType = Foo();                    // Will call MyType Foo()
object myObjectString = (string)Foo();    // Will call string Foo()

// Will call string Foo(), 
// or the 'simpliest' type (?) and warn the dev about possible ambigous call
// or at least won't compile for ambigous call
object myObject = Foo();

Parameter name based Method Overloading

EDIT: Well I discovered the new Named Arguments and Optional Parameters feature of C# 4, so... :D

public string Foo(string myString1, string myString2) { return myString1 + myString2; }

public string Foo(string myString3, string myString4)
{
     return myString3 ?? myString4;
}

string myStringR1 = Foo(myString1 "string1", myString2 "string2");
or
string myStringR1 = Foo(myString1 "string1", "string2");

string myStringR2 = Foo(myString3 "string3", myString4 "string4");
or
string myStringR2 = Foo("string3", myString4 "string4");

Why ? For constructors for example :

public Moo(string message, string reason) { ... }

public Moo(string message, string parameter) { ... }

Moo myMoo1 = new Moo("myMessage", reason "myReason");
Moo myMoo2 = new Moo("myMessage", parameter "myParameter");    

// Won't compile in this case : two string, string overload
Moo myMoo3 = new Moo("myMessage", "myParameter");    

-2

An exception-coalescing operator:

Instead of something like

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

Something like:

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

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

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

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

try {
    value = a;
} catch {
    value = b;
}
-4

Absolutely nothing.

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