Some blogs on the Internet give us several clues of what C# 4.0 would be made of. I would like to know what do you really want to see in C# 4.0.
Here are some related articles:
Channel 9 also hosts a very interesting video [6] where Anders Hejlsberg and the C# 4.0 design team talk about the upcoming version of the language.
I'm particularly excited about dynamic lookup and AST [7]. I hope we would be able to leverage, at some level, the underlying DLR [8] mechanisms from C#-the-static-language.
What about you?
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.
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"
}
}
}
float
. - Kyralessa
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.
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.
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.
Auto implemented property initializers.
public List<string> MyList { get; set; } = new List<string>();
All of the design-by-contract stuff from Spec#.
Seriously, it's awesome.
1) Record/Tuple return variables:
public { string ancestorType, int ancestorId } GetAncestorLookup()
{
//...do stuff
return new { ancestorType = var1, ancestorId = var 2 };
}
var ancIdent = GetAncestorLookup();
switch( ancIdent.ancestorType )
{
... and so on
2) Implied generics on class constructors [1]
3) More constraints for generics, for instance numeric:
public T SquareRoot<T>( T input ) where T: numeric
//or for collections:
public T Sum<T> ( IEnumerable<T> input) where T: numeric
public T StandardDeviation<T> ( IEnumerable<T> input) where T: numeric
Or possibly ones based on operator overloads:
public T Product<T> ( IEnumerable<T> input, T start) where T: operator *
{
T result = start;
foreach( T item in input )
result *= item;
return result;
}
Or ones for enums [2]:
public static bool IsSet<T>( this T input, T matchTo )
where T:enum //the constraint I want that doesn't exist in C#3
{
return (input & matchTo) != 0;
}
4) Internal (rather than private) anonymous types.
5) Strong (built into reflection) support for duck-typing. I want
object someObject = //...
IExpected duckTyped = Reflection.Get<IExpected>( someObject );
//or even
duckTyped = someObject as IExpected;
if( duckTyped != null )
duckTyped.InterfaceMethod();
This would work whether someObject's actual type implemented IExpected or not, so long as it could.
6) Equivalent for ?? on properties of nullable objects [3]
[1] http://stackoverflow.com/questions/45604/why-doesnt-c-support-implied-generic-types-on-class-constructorsNon 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;
}
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.
To be able to write binary values:
int myInt = (int)%00011011 | (int)%11111110 | myOtherInt;
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.
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.
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
My candidate would have to be point 4 from the anastasiosyal.com reference [1], "Safe Null Dereferencing Operator" .. The elegance that this could introduce in code that I've both written and seen is boggling. So that'd be my candidate for a most wanted feature for C# 4.0!
[1] http://anastasiosyal.com/archive/2008/07/19/4-features-for-c-4.0.aspxA 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...
}
I'm a nostalgist:
System.Error.BlueScreenOfDeath.Appear();
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#.
Named parameters
Reading code with calls to methods like MessageBox.Show, will be much more clear
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.
Three things.
public string Name { get {return field;} set { if(value==null) throw new ArgumentNullException(); field = value; } }
Adding an IArithmetic interface, which would be implicitly implemented by numerical primitives (int, double, etc). Currently it is not possible to do numerics with generics - you cannot even define a generic method like T add(T x, T y).
See also: Feedback ID 94264 on Microsoft Connect [1]
[1] https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94264Much 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);
Given that everyone hits [1] issues [2] with generics and things that should just work intuitively, I'd say that some implementation of contravariance / covariance for generic types would be great. If the types could be inferred by the compiler / runtime that would be brilliant, if I need to specify some syntax like in java, fine.
Eric Lippert has a great series of posts on this [3] and even suggests some syntax options (and asked people to vote for their favorite).
[1] http://stackoverflow.com/questions/110121/logic-and-its-application-to-collectionsgeneric-and-inheritanceMissing:
&&=
, ||=
, ??=
assignmentsNice to have:
?(a.B.C)
returns null if a is null.IEnumerable<>
$"All ${userName} bases are belong to us"
.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.
I would like to see some of the Design by Contract principles as a first class language feature, perhaps leveraging on method attributes which can instruct the compiler to wrap the method call with code which runs before and after execution (aka AOP)
EDIT: I had a useful chat with Anders at the PDC following his Future of C# talk [1]. He told me that they don't currently have an extensibility mechanism planned for C#, but the fact that a later C# variant will include the ability to call into the compiler means it would be fairly straightforward to decorate code with your own markup, and write a preprocessor which calls into the compiler and augments the code being compiled with whatever you like. Pretty much like IL-weaving, but done at the source level.
Still not ideal, as the debugging story would be flawed, just as it is with IL-weaving, because the source file no longer matches the compiled objects.
[1] http://channel9.msdn.com/pdc2008/TL16/public static T CallWithCurrentContinuation<T>(Function<Continuation,T> cc);
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;
}
All events should be weak events [1] by default.
Now, if A listens on B, existence of B prevents A from being garbage collected, ie. you can't be collected just because you are listening to someone.
[1] http://www.codeproject.com/KB/cs/WeakEvents.aspxIt's too late now but instead of LINQ [1] I would have loved to have seen some kind of list comprehension (such as in Python or Haskell). It has the same expressive power but uses a more lightweight syntax.
[1] http://en.wikipedia.org/wiki/Language_Integrated_QueryTraits. 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)
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.
I hope this isn't already in there, but I just stumbled back across a teeny tiny annoyance such that when using out
parameters for a method you need to have the variable holder declared already.
It would be nice to use a method with an "out" parameter and declare it at the same time (ideally using the var keyword).
// Function
public bool TryParse(string value, out int value)
{
...
}
// Caller
if (TryParse("123", out var value))
{
...
}
As opposed to the current calling code:
// Caller
int value;
if (TryParse("123", out value))
{
...
}
NOTE: Please correct me if I'm wrong and it's already in there!
Better internal keyword.
Internal now only works at assembly level. I would like to be able to make more specific access restrictions:
Why do I need that? For cleaner encapsulation. I don't want to divide my project into many assemblies, yet I need eg. to have a class that is read-only to the outside, but only special "friend" builder class can modify it. See C# builder pattern [1]
Scala programming language supports this.
[1] http://www.c-sharpcorner.com/UploadFile/rmcochran/instantiationBuilder06232007171715PM/instantiationBuilder.aspxI 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.
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;
}
}
Static extension methods - extension methods for classes themselves, not only for objects.
public static class MyExtendingClass {
// Regular extension method
public static void Save(this String st, String filename)
{
// writes st to filename
}
// Static extension method
public static String Open(static this String, String filename)
{
// returns string read from filename
}
// Extension constructor
public static MyDataType(static this String, String filename)
{
var data = new MyDataType();
MyDataType.LoadStateFrom(filename);
return data;
}
}
Usage:
String st = String.Open("myfile.txt"); String.Save("yourfile.txt"); MyDataType data = new MyDataType(filename);
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.
Having a Me generic type in all classes. For example I currently have the following:
public abstract class Foo<T> where T : Foo
{
public T Activate();
}
Meaning I have classes like:
public Bar : Foo<Bar>
{
public override Bar Activate();
}
It would be nice to say something like:
public abstract class Foo
{
public abstract ?Me Activate();
}
A further feature would be:
public class Foo where ?Me : new()
{
private Foo ActivateNew()
{
?Me result = new ?Me();
result.Initialize(...);
return result;
}
}
I would like to see full Microsoft support for C# / .NET / CLR on all popular hardware platforms.
I understand Mono [1] does this (and I am very grateful), but having Microsoft directly support the project would be a big deal as well.
[1] http://en.wikipedia.org/wiki/Mono_%28software%29Automatic 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();
}
}
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();
Indexed properties.
Currently, a (single) indexer can be defined for a class to access data by index, but index parameters cannot be added to individual properties. Something like this:
class Foo
{
public string this[int index] { get; set; } // indexer
public string Bar[int index] { get; set; } // indexed property -- unsupported
}
Foo f;
string a = f[0]; // use class indexer
string b = f.Bar[0]; // use indexed property -- unsupported
Managed C++ and C++/CLI both support indexed properties -- strange that C# does not. This MSDN page describes a somewhat-clumsy workaround for C#: http://msdn.microsoft.com/en-us/library/aa288464(VS.71).aspx [1]
[1] http://msdn.microsoft.com/en-us/library/aa288464%28VS.71%29.aspxIt is often (rightfully) noted that interfaces are not contracts [1], and constrain nothing but class semantics, not behavior. How about "Contracts" being a combination Of .NET 4.0 CodeContracts Pre And Post Conditions and interface like signature definitions providing for true contracts and truly verifiable code in .NET.
public Contract IList<T>
{
Add(T item)
{
// Pre and Post Conditions
}
int Count {get;}
}
[1] http://blogs.msdn.com/kcwalina/archive/2004/10/24/246947.aspxHow about something like anonymous interfaces?
Example:
interface IFoo
{
int Bar {get;set;}
}
IFoo foo = new IFoo { Bar = 1 };
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.
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.
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
Multiple/generic setters for properties:
private Uri _linkUrl;
public Uri linkUrl
{
get { return _linkUrl; }
set
{
_linkUrl = value;
}
set<string>
{
_linkUrl = new Uri(value);
}
}
//this of course works fine
MyObj.linkUrl = new Uri("http://stackoverflow.com");
// but I could also just do this:
MyObj.linkUrl = "http://stackoverflow.com";
Also see the discussion with this other question. [1]
[1] http://stackoverflow.com/questions/516981/what-features-do-you-wish-were-part-of-c/517040#517040I 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
}
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.
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.
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.
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;
}
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>
Anonymous types should be interfaces instead of sealed classes. It should then be up to the LINQ provider to generate the type as it sees fit.
Then when you do a projection with my LINQ library, I could return an object implementing INotifyPropertyChanged.
I'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);
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
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.
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.
Fascinating talk by Anders at the PDC:
It looks like C#4 will support:
I put in a feature request for ruby-style blocks [1].
[1] https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=369334How 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.
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);
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.
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.
Generic type partial specialization.
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.
Primative/Struct template unsafe methods.
Example:
private unsafe ModifyStream<T>(byte[] stream) where T : primative/struct { fixed (T* ptr = stream) { ... } }
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.
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);
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!
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.
Something to let me use all of the sub-namespaces in a namespace, ideally something like this:
using System.*;
Not particularly of interest, but it would be nice to go
Foo foo = new(bar, "baz");
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
.
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.
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.
Would be interesting if I could do, inside the context of Dynamic Lookup (a feature to come with C#4), something like that:
dynamic
{
object dynamicObject = GetDynamicObject();
string method = "Foo"; /* or a call to somewhere in order to initialize this string */
dynamicObject.method(); /* in this case, it means 'dynamicObject.Foo();' */
}
The goal of DLR is to ease the way we use reflection in C#. Since this construct can't compile in normal C# (object.stringIdentifier() ?), could inside a C# 4 dynamic block do this to improve reflection usability.
I know that according to the definition I saw on this article [1], this should call a method named 'method'. But when there is an identifier on the block with this name, could be more interesting to the developer to use this information. This identifier could refer basically to a string, but pottentially to other objects with more method info.
[1] http://blogs.msdn.com/charlie/archive/2008/01/25/future-focus.aspxA ReadMyMindAndBuildApplication() method - that could be neat.
Or XML Literals like in VB.NET.
I would like to be able to cast between arrays of unmanaged types [1] without the need for unsafe code and fixed pointers. There are some hacks that you can use to do this (explicit layout structs), but language support would be great.
float[] floatArray = (float[]) byteArray;
[1] http://mark-dot-net.blogspot.com/2008/05/wanted-language-feature-reinterpret.htmlI'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++; }
}
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
keyword)in
and out
keywords)There is more, but this covers most of the features that people were asking for that will be in the next release.
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;
}
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?
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
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.
I want direct access to low level system APIs and never don't "to dirty the hands" with c++ :-)
Methods that must be private and can only be called from constructors and other such methods, but can modify readonly fields.
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.
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
}
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);
}
}
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.
}
}
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