Hi and welcome to my blog. Im Tasos, a software engineer working in the UK. This is where i share some of my findings related with SQL, c#, asp.net and javascript with you. I hope you find something helpful and Im looking forward to your feedback!

Recent Comments

Popular Posts

Recent Posts

Archives

Post Categories

Blog Stats

  • Posts: 15
  • Comments: 80
  • Trackbacks: 9
  • Articles: 1

4 Features for C# 4.0

Saturday, July 19, 2008 1:26 AM,

Plenty of powerful new language features have fairly recently become mainstream with the launch of VS 2008 in Nov 2007 that supports C# 3.0, amongst which:

  • Implicitly Typed Local Variables
  • Extension Methods
  • Lambda Expressions
  • Object and Collection Initializers
  • Anonymous Types
  • Query Expressions
  • Automatically Implemented Properties

Although most of us are still trying to fully absorb the above features, there has been some speculation going on about what sort of features we would like to see in the next version of C# and Jeremy Miller has posted a question with what he would like to see.

Here are some of the language features I would really like to see in C#:

1. Implementing Interfaces by delegation to fields

I would like to see support in C# 4.0 that would allow us to delegate the implementation of an interface to a field in the implementing class. For example this could look something like the following:

    //faux code
    public class Foo : IList<string>
    {
        private List<string> _Collection implements IList<string>;

        public Foo()
        {
            _Collection = new List<string>();
        }
    }

The field could be delegated to implement one or more interfaces from the encapsulating class by separating them with a comma. This would remove a lot of redundant code in scenarios like the above one, ie. Instead of implementing a lot of pass through functions on the encapsulating class (Foo) the functions are directly mapped to the delegated interface implementation. This sort of functionality would also enhance support for mixins 

This is known as the delegation pattern and from wikipedia:

The delegation pattern is a technique where an object outwardly expresses certain behaviour but in reality delegates responsibility for implementing that behaviour to an associated object in an Inversion of Responsibility. The delegation pattern is the fundamental abstraction that underpins composition (also referred to as aggregation), mixins and aspects.

Taking it one step even further, one could override the delegated implementation in a syntax like so:

    public class Foo : IList<string>
    {
        private List<string> _Collection { get; set; } implements IList<string>;

        public Foo()
        {
            _Collection = new List<string>();
        }

        //This would override the delegated implementation 
        // for nice mixin functionality and easy decorator pattern implementation
        public int IList.Add(string value)
        {
            if (!_Collection.Contains(value))
                _Collection.Add(value);
        }
    }

2. Anonymous type return values

I would like to see the anonymous types becoming first class 'citizens' in C#. Anonymous types can only be used in a local scope and cannot be returned from functions. It would be nice if we could return our strongly typed Linq Query Projection from a function eg:

        //faux code
        public var GetProductInfos()
        {
            var productInfos =
                from p in products
                select new { p.ProductName, p.Category, Price = p.UnitPrice };

            return productInfos;
        }

 

3. Some Duck-typing or Structural Subtyping support

If a class has a property or a method signature that is the same as the method signature on a declared interface, then that class implicitly implements that interface, if it is not already inheriting from it.  The class would implicitly implement an interface if and only if it would implement all the method signatures of a given interface. Basically

if it walks like a duck and it quacks like a duck, then I would call it a duck! (James Riley)

So what is the difference with Structural Subtyping? I would argue that structural subtyping is more suitable to the static style of C#, since it is a 'static duck typing', or according to wikipedia:

Duck typing differs from structural typing in that only the part of the structure accessed at run time is checked for compatibility.

Lets see how this could be beneficial through a use case:

The .Net framework has a few controls that implement a ReadOnly property amongst which are the TextBox, DataGrid, NumericUpDown.

Lets define the IReadOnlyRestrictable interface in our source like so:

        public interface IReadOnlyRestricable
        {
            bool ReadOnly { get; set; }
        }


Let's assume that we wanted to Loop through all the controls on a form and anything that satisfies the above interface signature (i.e has a property 'ReadOnly') set its readonly property to true. With ducktyping the qualifying controls would be cast to a valid IReadOnlyRestrictable instance like below, without needing to resort to reflection

        foreach (Control c in f.Controls)
        {
            //would like to have implicit cast to IReadOnlyRestrictable if interface contract is in class we are checking against
            IReadOnlyRestricable editable = c as IReadOnlyRestricable; 
            if (editable != null)
                editable.ReadOnly = true;
        }

The main advantage I see with ducktyping is that you can declare interfaces for libraries that you do not have access to, this can be useful in scenarios where you would like to minimise dependancies, check out Phil Haacks more extensive post on duck typing and why he believes it would benefit C# developers.

Apparantly, the c# foreach operator already uses duck typing according to Krzysztof Cwalina

 

4. Safe Null Dereferencing Operator

I would really like to see a safe way to dereference a null value in an expression that of form Object.Property.Property.Value.

For example if we had Customer?.FirstName and Customer was null, then the expression would evaluate to null instead of raising a null reference exception.
Some more examples of how this could work:

    //FAUX CODE
    //this would throw a null reference exception as usual if either Customer or Order was null
    int orderNumber = Customer.Order.OrderNumber;

    //this would not compile since it would require a nullable return type
    int orderNumber = Customer.Order?.OrderNumber;

    //this would return null if a Customer was null or if Order was null 
    int? orderNumber = Customer?.Order?.OrderNumber;
    if (orderNumber.HasValue) 
        //... do something with it

    //instead of having to do 
    if ((Customer != null) && (Customer.Order != null))
        int a = Customer.Order.OrderNumber

 

Wrap up

Here is a recent interview of the C# 4.0 team in the room where all the magic happens

What is your take? Do you agree? What features you would like to see?

Share this post!
digg it
Kick it on DotNetKicks.com

Comments

# re: 4 Features for C# 4.0, Posted by Mike Borozdin on 7/21/2008 8:44 AM

[quote]Anonymous type return values[/quote]

That is no good. How can I learn which type it is going to return? What about IntelliSence? What about documentation? What about error checking during compilation?

# re: 4 Features for C# 4.0, Posted by Anastasiosyal on 7/21/2008 9:35 AM

Hi Mike and thanks for your comment,
I dont see an issue with Intellisense and anonymous return values, it would work similar to the way as it works currently, check out this image:

http://anastasiosyal.com/images/anastasiosyal_com/WindowsLiveWriter/C3.0Anonymoustypesupportisincomplete_28BB/image_thumb.png

And again, this is just an option, it wouldnt stop us from still creating solid classes where we need them. Personally, I see the value of returning anonymous types especially in the case of returning Linq Query Projections. Why would i want to create solid classes that are mere placeholders for my LINQ projections? Each time i would need to add or remove a field I would have the unnecessary burden of synching its corresponding class. Multiply this by the number of queries that your application has to do and then we are quickly creating unnecessary maintenance overhead for ourselves. I think things could be simpler, and this could definately help to that end.

Anastasiosyal


# re: 4 Features for C# 4.0, Posted by Mike Borozdin on 7/21/2008 9:44 AM

My next thought is that matter of the language philosophy. C# is a strongly typed language. LINQ, var, anonymous types haven't made it dynamically-typed language, it still remain strongly-typed. But the thing you suggest is very different. Return and parameters types are the necessary attributes of strongly-typed languages. You want to remove it.

>Why would i want to create solid classes
>that are mere placeholders for my LINQ projections?

What is a problem with that? I guess you have some business object, so put your LINQ projection there.

# re: 4 Features for C# 4.0, Posted by Anastasiosyal on 7/21/2008 11:32 AM

Thanks for your followup,

I agree that C# is a strongly typed static language. Anonymous types are not dynamic types, they are statically created by the compiler. If you open up an assembly with Reflector you can even notice the definition of the anonymous types. They are called anonymous because instead of me going explicitly to my project to code a DTO class with a name Products and members ProductName, Category and Price I leave this for the compiler to generate. I dont see the advantage of having to maintain such a DTO class whose purpose is simply to hold a projected view of readonly data. The compiler can do it for me and I can go home earlier :)
Now if the class should have some sort of logic in it, i agree that it should be handcrafted by the developer, otherwise i see it as needless maintenance overhead.

Anastasiosyal

# re: 4 Features for C# 4.0, Posted by Nick Leaton on 7/21/2008 1:35 PM

It has to be DBC (design by contract).

You really need the compiler and language modified for this to work. The advantage is that it is all code is backward compatible by default.

There are lots of reasons. First is the growth of things like Pex for testing. Having the contracts makes life easier for the automatic tester.

Secondly, consider unit testing. Invariably this is just writing code that sets up data in line with preconditions and then asserts post conditions. It is only run once. Far better to have the assertions tested all the time whilst deveoping.

It is also a prerequisite for nice multitasking.

Consider a queue. There is a precondition of "not empty" on pop. In a multitasking set up, the consumer would wait until the precondtion was satisfied before carrying on. ie. The same code in a single threaded set up also works in a multithreaded set up. Search for Simple Concurrent Object-Oriented Programming (SCOOP) for details.

# re: 4 Features for C# 4.0, Posted by Jay R. Wren on 7/21/2008 3:02 PM

I love these.

@Mike Borozdin:
Consider F#'s definition of methods(functions). It is just as strongly typed as C#, yet the compiler is left to infer the return type.

In the example above the return type is not weak, it is not vague or dynamic or relying on duck typing. The return type is the anonymous type defined by the select clause of the linq statement. All of the static type checking and strength of warnings and errors of the compiler will still occur.

I'd like to see similar syntax, but drop the var, it is needless noise.

e.g.

public GetFirstPageOfFiles(string dir)
{
return Directory.GetFiles(dir).Take(10);
}

The signature of the method GetFiles takes a string and returns a string so we (and the compiler) KNOWS that GetFirstPageOfFiles returns a string.

But have we simplified the langauge as much as we can? F# wouldn't make me specify the type of the argument to the method. It would infer it.

public GetFirstPageOfFiles(dir)
{
return Directory.GetFiles(dir).Take(10);
}

Again, the argument to GetFiles is string so the compiler knows how to turn the method signature of

public GetFirstPageOfFiles(dir)

into

public string GetFirstPageOfFiles(string dir)

Where the compiler can't infer, it should give an error and require the explicit use of the type.

This exactly the behavior of var now.


As for #3, I would NOT want this to be the default behavior. The default behavior should be strong-static types. As strong and as static as possible. That said, some compiler support for the equivalent of duct typing via reflection would be rather nice. AFAIK what you are asking for is already available through a 3rd party library from David Meyer at http://www.deftflux.net/blog/page/Duck-Typing-Project.aspx

With respect to default behavior being duck, Phil Haack is wrong, everyone is wrong. If you want that, use Iron Ruby or Iron Python.

I wrote about my uncertainty about the GetEnumerator duck here: http://jrwren.wrenfam.com/blog/2007/07/21/c-has-duck-typing/ It may have been necessary. If it wasn't necessary, I'd call it a mistake. Maybe it was an accident. I don't know.

# re: 4 Features for C# 4.0, Posted by Shawn Poulson on 7/21/2008 3:04 PM

I think C# could benefit more from integrating more tools, and less on removing syntax verbosity.

For example, I seriously miss C++'s templating and multiple-inheritance power.

For example, it would be so nice to inherit from multiple abstract or concrete classes that contain utilities, such as utility implementations for various interfaces (IDisposable, IEnumerable<>, etc.). Instead, I'm forced to duplicate code if my class already inherits from a non-interface class.

# re: 4 Features for C# 4.0, Posted by Daniel on 7/21/2008 3:13 PM

All good ideas. One I'd like to see is improvements to automatic properties that enable more advanced scenarios:

public class MyClass : INotifyPropertyChanged
{
public PropertyNotifier notifier = new PropertyNotifier() implements INotifyPropertyChanged;
public string MyProp {get;set;}
}

Ideally would "just work", though some simple language construct would be fine too.

# re: 4 Features for C# 4.0, Posted by Pop Catalin on 7/21/2008 4:29 PM

I would personally like the C# team to extend the Safe Null Dereferencing Operator to include the coalescing ?? operator like so:

int orderNumber = Customer.Order?.OrderNumber ?? -1;

So in this case it can work with non nullable types and can be an overall more powerful language feature that can return an arbitrary object or value in case of a null in the hierarchy.

Actually this might work by default as ?. returns null and the coalescing operator ?? accepts a nullable type as first argument :) .

Might be interesting if it will work on methods also not only properties:

int? orderNumber = customer?.GetOrderNumber();

but this might be the next big bug hiding feature so I'm not sure it's really good:
foo1?.Foo2?.Foo3.Bar4?.Bar5?.GetFoo(GetBar("Foo"))?.Address?.Street.Name
"NullReference exception was thrown..."
say what?


Anyway a bunch of nice features coming, but I for one I'd trade all of them for public anonymous types that can be used as return values.


# re: 4 Features for C# 4.0, Posted by Jon von Gillern on 7/21/2008 6:55 PM

I totally agree on the duck typing post. I wrote something similar last November

http://www.vonsharp.net/RetroactiveInterfacesStrongDuckTyping.aspx

# re: 4 Features for C# 4.0, Posted by Anastasiosyal on 7/21/2008 8:12 PM

@Nick

I agree, Design By Contract is very important functionality that when used correctly can minimise bugs in code and goes inline with your testcases. Spec# has already made progress in this field showing how this could potentially be done in the future. Having said this, DbC can already be applied to c# to some extent via attributes:
LinFu Design By Contract
Spec Sharp


@Jay R. Wren

Very good point about #3. I too agree that this feature should not probably be the default behaviour. The example could then be something like
IReadOnlyRestricable editable = c as implicit IReadOnlyRestricable;

Or something like that

As for the var keyword, superfluous though it may seem, I still think that it should be explicetly stated that a method returns an anonymous type. I think that when declaring types and class/interface contracts c# should maintain its explicit style. When consuming those contracts implicit can fit nicely (for example, lambda expressions)

@Shawn:
I am also on the side that would like Multiple inheritance for scenarios such as you describe. However, this looks like one of those fundamental design decisions that are taken at the beginning, i dont think c# will do multiple inheritance in the future. Composition of functionality could be addressed with better mixin support (point #1) as an alternative to multiple inheritance.

# re: 4 Features for C# 4.0, Posted by Judah Himango on 7/21/2008 8:14 PM

Duck typing? Safe null dereferencing?

Come on guys. Those are nice things, but not critical by any means.

I'd much, much rather see something that would help us write less-buggy code, such as design-by-contract attributes with compiler enforcement, ala Spec#.

[Pure]
string GetFoo(string baz, int bar)
requires baz != null && baz.Length > 0
requires bar > 0
ensures return != null;
{
...
}

This would eliminate a wide range of programming defects. How much greater importance is that than niceties like duck typing and null dereferencing!

# re: 4 Features for C# 4.0, Posted by Konrad Drukala on 7/21/2008 9:09 PM

This 'var' in method signature is a disaster.

public var Something ()
{
if (condition) return 3;
else return "3";
}

it will presumably lead to increase in bad code. Not everyone is a great developer and I'm pretty sure that we will see some monsters like that.

# re: 4 Features for C# 4.0, Posted by Anastasiosyal on 7/21/2008 9:22 PM

Hi Judah,

Thanks for your reply. I posted this entry keeping minimal syntactic requirements in mind that could be realistically achievable for the next version (or at least as i would like to think so :-)

Personally i dont see what you suggest being the eliminator of a wide range of progamming defects. The only reason being is that I can easily implement my preconditions and postcondition checks within my functions unless im missing something. Of course, I definately see this as a nice to have feature that would add value to our projects by simplifying the implementation of pre/post condition checks and their readability.

logicalmind has posted a nice question over at dotnetkicks to the thread you started asking about how would the compiler guarantee purity? It would seem that in order to mark a method as pure all the methods that are called inside of the method must also be pure. So essentially every library call all the way down to some level (system calls???) have to be verifiably pure. How does this happen?

Rewriting the .Net Framework in a way that can guarantee purity doesnt seem like a simple task!

# re: 4 Features for C# 4.0, Posted by Anastasiosyal on 7/21/2008 9:36 PM

Hi Konrad,

The sample code you have provided would not compile.
Just as in C# 3 this does not compile:
var i = 1;
i = "1";

OR
it would compile by evaluating the method signature to the closest ancestor of the return types class hierarchy. So in essence your example would be statically evaluated by the compiler to:
public object Something () etc

I would rather the compiler would generate an error since i see such a feature should only be used for returning genuinly anonymous types. If one would like to return polymorphic values then they should declare a concrete type as return value.

# re: 4 Features for C# 4.0, Posted by Judah Himango on 7/21/2008 10:27 PM

Anastasiosyal,

Spec# already provides annotations for the existing .NET framework. It's already done. :-)

# re: 4 Features for C# 4.0, Posted by Paco on 7/22/2008 12:17 AM

I think these four features are must be a very good source of inspiration for the MS C# team. Great post! Keep up the good work.

# re: 4 Features for C# 4.0, Posted by Darrell WRight on 7/22/2008 7:26 AM

How about something like Numeric generics. It's been requested since 2.0 I believe. Being able to do +-/* on classes passed to a generic class would make C# generics very powerful and remove another need of C++. Something like an interface INumeric.

# re: 4 Features for C# 4.0, Posted by Buu Nguyen on 7/22/2008 10:01 AM

@Konrad Drukala:
If this feature is to be implemented, the code you describe will definitely not compile. Under the hood, the compiler still need to spit out a plain old type for the method signature, and it can't be 'var'.

# Interesting Finds: 2008.07.24, Posted by gOODiDEA on 7/24/2008 12:51 AM

DebugManagedThreadPoolvsWin32ThreadPool(pre-Vista)WebDOMDocumentFragments-document.crea...

# Interesting Finds: 2008.07.24, Posted by gOODiDEA.NET on 7/24/2008 12:53 AM

Debug Managed ThreadPool vs Win32 ThreadPool (pre-Vista) Web DOM DocumentFragments - document.createDocumentFragment

# 今天看到的好文,很不错,特别是那漫画。, Posted by 真见 on 7/25/2008 12:01 PM

感谢Gray Zhang 的再次帮助,C#4.0的四个新特性由他大致翻译。

# , Posted by YESChandana -Blog on 7/27/2008 11:22 AM

My favorite links from the last week (20/07/2008 - 26/07/2008)

# , Posted by YESChandana -Blog on 8/3/2008 12:15 PM

My favorite links from the last week - 5th Week of July 2008

# , Posted by YESChandana -Blog on 8/3/2008 12:17 PM

My favorite links from the 5th Week of July 2008

# re: 4 Features for C# 4.0, Posted by free C# ebooks on 10/23/2008 11:22 AM

I have searched the net and I should say I have not come across an article like this which is so easy to understand and learn the concepts.
cheers

# "var" as return type is problematic, Posted by Kannan Goundan on 10/29/2008 9:18 PM

Full-blown "anonymous type" support would require a notation to describe anonymous types. Something like:

{string ProductName, string Category, int Price}

C# 3.0 got away without that because they didn't allow anonymous types to escape a function. The compiler can see all the code in a function all at once, so it can do the inference locally.

Putting "var" as the return type of a public function is problematic for several reasons. For one, it's not universally applicable. For example, let's say you had the interface:

interface DataGetter {
public var GetData();
}

DataGetter g = ...;
var x = g.GetData();
Print(x.Hello); // Error or not?

The function signature for GetData is underspecified.

If you want to allow this only for non-virtual methods, then the compiler can infer the type. But now, for the first time in C#, you are no longer specifying the interface and implementation separately. Normally, you fully specify a function's signature, which allows the compiler to check if the body of the function obeys the signature. With "var", you don't have that safeguard.

Local type inference is fine because its effects don't leak outside your public interface.

Functional programming languages like Haskell and F# support type inference for public functions but most programmers explicitly specify a type signature as well. This makes your module's API more resilient to implementation changes.

# re: 4 Features for C# 4.0, Posted by headman on 10/31/2008 1:53 PM

Thank you! Definnitely agree.

# re: 4 Features for C# 4.0, Posted by geirnt on 11/1/2008 9:00 PM

I have searched the net and I should say I have not come across an article like this which is so easy to understand and learn the concepts.

# re: 4 Features for C# 4.0, Posted by Gerbil on 11/3/2008 10:35 PM

An anonymous return destroys any chance of static analysis consider:

var Proxy( bool call_a ) {
if ( call ) {
return CallA( );
} else {
return CallB( );
}
}

What is the return value? What if CallA is anonymous also? Does intellisense have to compile the world to figure this out?

# re: 4 Features for C# 4.0, Posted by Peter Verswyvelen on 11/9/2008 3:10 PM

A feature I really miss (and the WPF team must have missed this too...) is the ability to get the name and RTTI of properties (and methods), directly. Properties are really just syntactic sugar in C#, while they should be first class citizens...

for example

public class Book
{
public string Title { get; set; }
}

How do I get the name of the Title property? I don't think I can in C# 3.0. I have to use a literal "Title" string to refer to the Book's Title property. So say goodbye to refactoring tools, since the refactoring tool can't know that "Title" is actually referring to Book.Title... Why can't I do nameof(Book.Title)? Or typeof(Book.Title).Name? If I recall correctly, the Digital Mars D language has support like this.

Furthermore, I can't access the getter or setter methods behind a property in C#. This means properties can't be used as delegates. For example, if my Book class would look like this:

public class Book
{
private string m_Title;
public string GetTitle() { return m_Title; }
}

then I could use book.GetTitle as a Func<string> delegate. But I can't use the Title property directly like that, I would have to wrap it in a weird lambda like (() => book.Title). I would like to have access to the underlying get/set methods, like book.get_Title, or have a language extension that allows this, like book.Title{get} or something.

Also, in C# I don't know a way of calling a method of a specific base class. I can do that in CLI/C++, but not in C#, so it certainly is not a CLI limitation.

Next, generics don't allow a generic parameter to be used as a base class. So all the goodies that ATL gave us can't be simulated in C#.

And I really miss the "const" keyword from C++. For example, the ReadonlyCollection is just a wrapper that throws an exception when you try to mutate it; I would prefer to catch these errors at compile time.

# re: 4 Features for C# 4.0, Posted by Peter Verswyvelen on 11/9/2008 3:20 PM

Oh, and I forget my most wanted feature: inner "instance" classes, like in Java, meaning that an instance of a inner class has an implicit reference to the parent instance that created it (just like "this" refers to the instance itself). This allows for very nice implementations of state machines, and many more things that Java solves without delegates.


# re: 4 Features for C# 4.0, Posted by hot girls on 11/16/2008 1:39 AM

I think these are all great ideas, I really like #2. Returning var instead of a specific type is very appealing.

Make me wonder about the noobs that start learning c#, they will be confused perhaps by a lot of this.....

Amber,

# re: 4 Features for C# 4.0, Posted by Skrilax on 12/2/2008 9:50 PM

hot girls: Noobs will be confused and will start misusing dynamic type much more than this.

So to sum this up:

#1 I see the point. However I would add "override" keyword to the last example i.e "public override int IList.Add(string value)" in the last example.

#2 This sounds a bit confusing to me. You - the maker of the function - still know what it returns so I don't see the point there. However it may not be as clear to the client programmer or whoever uses the method though. I find this to be just too much lazivness :)

#3 This is a bit speculative. However I would still require the "as" operator to keep things easier to read.

#4 This would be a nice feature.

# re: 4 Features for C# 4.0, Posted by Marcos Boyington on 4/26/2009 4:36 PM

All great features, except for #2 heh. Although I will agree that only #1 is a major one.

The problem with #2 is assemblies and such. What would a compiled assembly with a var function look like? It would have to change the var to the appropriate return type, which in itself would be a bit strange (the assembly metadata would look different than the function declaration, could open a can of worms).

Some other things which are missing from C# which definitely need to be added:

* Typedef would be nice

* Fix CS0404: attributes cannot be generic - this limitation needs to be removed

* Some other additions to make C# more static-friendly. For example, it's currently not possible to get a PropertyInfo or MethodInfo statically. It would be really nice to have typeof(SomeClass.SomeProperty) and typeof(SomeClass.SomeMethod) return a PropertyInfo and MethodInfo respectively.

# re: 4 Features for C# 4.0, Posted by survivor on 5/4/2009 2:32 PM

asfasf

Comments

Title: *
Name: *
Email: (never displayed)
Website:
Comment: *  
Please add 8 and 4 and type the answer here: