C# Func<> delegates in library - c#

The generic Func<> and Action<> delegates from later versions of .NET are very appealing, and it's been demonstrated in many places that these can easily be recreated in code targeting .NET 2.0, such as here.
From the perspective of a library targeting .NET 2.0 however, which may be consumed by applications built against any higher version of .NET, how does this stack up. Is implementing this "compatibility layer" within the library absolutely a recipe for conflict (both in terms of private and public interface), or are there ways to make this work independent of the target framework that the consuming application builds against?
If this is a non-starter, would it be better to either:
A) Define an identical set of parametrized delegates with different names? or..
B) Stick strictly with .NET 2.0 convention, and define new delegate types as I need them?

The plain truth is that Func<> and Action<> are a good idea. They make your code much easier to read and they avoid a shocking amount of messy boilerplate delegate declarations. That's why you want to use them.
So you have this really appealing programming style you want to use, it's a standard technique that is now used almost universally instead of the old way, but you can't use it because you are targeting a legacy version of the framework. What should you do?
You have three choices:
Use the programming style that was in common use before the feature
Add the feature to your own code in spirit but with non-conflicting names
Add the feature to your own code with the "real" names but in your own namespace
Using the old programming style gives up all the benefits that we have come to appreciate from the feature. That's a big sacrifice. But maybe all your co-developers are used to this style of programming.
Using the feature with non-conflicting names seems sensible enough. People will be able to read the code and benefit from the features, but no-one will be confused that they appear to be something that they're not. When you are finally ready to upgrade, you'll have to patch up the names. Luckily Ctrl+R, Ctrl+R makes doing that very easy.
Using the feature with the same names as the standard feature means your code can target an older version but appear to be using newer features. Seems like a win/win. But this could cause confusion and you have to be careful that your types aren't exposed to other unknowing assemblies, possibly causing source level compilation problems. So you have to be careful and be perfectly clear about what is happening. But it can work effectively.
You have to pick whatever approach makes sense in your situation depending on your needs. There is no one right answer for everybody, only trade-offs.

Related

Why should I upgrade to c# 4.0?

I know there are some nice new features in C# 4.0 but I can't, for the life of me, think of a compelling reason for either upgrading existing projects or for switching to new projects.
I've seen some posts where people have said that if their hosting service didn't provide .Net 4 that they'd find another provider as .Net 4 was pinicle to their direction <?>.
Now my boss is trying to get me to agree to switch all our production environments to C# 4 and to do it now.
So the question is has anyone either began using, or converted a project to, C# 4 for a compelling reason? Was there a feature that you just had to have that would make your life so much easier?
There are some cool new features in C# 4.0:
Dynamic member lookup
Covariant and contravariant generic type parameters
Optional ref Keyword when using COM
Optional parameters and named arguments
Indexed properties
In his release blog post Scott Guthrie goes into detail about the features of .NET 4 in general. Another great resource is a white paper at http://www.asp.net/learn/whitepapers/aspnet4. However, I'd doubt you are going to need one / any of these new features right away. As Scott Hanselman blogged:
there's a lot of stuff that's new and
added in .NET 4, but not in that
"overwhelming-I-need-to-relearn-everything"
way.
Whether or not you should upgrade is therefore dependent on a variety of other factors. Some reasons that spring to mind:
Standardizing your development environment on a single platform VS2010 over VS2008.
Size of the .NET Framework is substantially reduced
Speed improvements if you are a Visual Studio Tools for Office developer
An open dialogue with your manager seems appropriate to understand his reasoning for the upgrade. I'd argue that because it's shiny isn't a compelling reason.
As a reference this dated Stack Overflow question "Why not upgrade to the latest .net framework" provides the inverse to your question.
Quite frankly System.Collections.Concurrent has made developing multi-threaded applications a breeze.
The new and improved System.Linq.Expressions makes writing dynamically compiled code seem like child's play.
The new named parameters feature means I can have big constructors and not get confused as to what each parameter is. Immutable objects are just that much easier.
Surprisingly not mentioned:
PLINQ
Task Parallel Library
Is your question specific to C# 4.0, or .NET 4.0?
In C# 4.0 there are only a couple of really nice new features. Covariance/contravariance is not useful all the time, but when you run into a need for it, it can really save a lot of pain. Optional method parameters can reduce a lot of ugly method overrides, and make certain method calls a lot cleaner. If you're using COM or IronPython or any of a few similar frameworks, the dynamic keyword can also be a real lifesaver.
.NET 4.0 in general has a ton of really interesting features across a variety of frameworks. Foreign Key support in Linq to Entities, for example, is making life a lot easier for us. A lot of people are really excited about POCO support. They also added support for some of the LINQ methods (e.g. Distinct) that were previously missing from the Entity Framework.
So it will really all boil down to which frameworks you're using and how you're using them, and how expensive it will be for you to make the switch.
First, what is compelling to me may mean nothing to you. Having said that, I would upgrade Visual Studio if budget allows. In fact, personally I think there is a huge career risk in staying with a company that doesn't keep your tools up to date. You will fall behind in your knowledge of the field without access to the latest tools.
As for converting all your projects just to convert them it seems like folly to me. Putting aside all the extra work distribution (and upgrading the machines to have .NET 4), you have to consider the chance that you will have something go wrong. (And if you are like me some things must be called from 3rd party programs using .NET 3.5 making them unable to convert.)
My first rule would be that nothing is converted unless you are working on it anyway. But I would seriously look to convert anything that could use improvement from either parallel code, or COM interop.
I do have a compelling project that was converted. I had a long running web method being called. In the version that exists now, I return from the method without knowing the results. Instead I gave the user a way to check later. By moving to a parallel foreach loop this works much better and I can let the user know if there were any errors.
The same project is also being converted to use RIA services which have greatly improved and reducing the amount of my own code.
I upgraded for the same reason everyone else did.
...so I can put it on my resume :)
If you're starting a new project today, it's probably best to start it on 4.0, since down the road you will have to migrate it at some point anyways (assuming it stays around long enough, older versions of .net will simply stop being supported).
C# 4 implies other things.. depending on your project... WCF 4, WPF 4, ASP.NET 4, MVC 2, Entity Framework 2, etc.. So don't just look at C# as the reason to change, you also have to look at the whole stack. If there's still nothing compelling, then staying where you're at is probably a wise choice.
If you're doing WPF / Silverlight, I would definitely recommend upgrading to Visual Studio 2010 (I know, you can write .NET 4.0 code without an IDE, but that's an edge case if ever there were one).
The multi monitor support is nifty but buggy. I spend a lot of time trying to get windows to refresh.
In terms of language, the COM interop (as #Gvs mentioned) is also vastly improved with the dynamic datatype and optional parameters.
UPDATE: Multiple monitor support is pretty rock solid with VS 2010 SP1.
If you can get your boss to pop for the $10,000+ Visual Studio Ultimate Edition, IntelliTrace is a compelling reason to upgrade your environment and justification enough the for investment.
COM integration is much easier with the dynamic datatype, and optional parameters.
For me there are two things:
optional arguments -- because I am sick of polluting classes with X versions of the same method (overloading)
dynamic keyword -- because the expressiveness of generics in C# is a joke, this way I can at least "write what I mean" without hoops, of course with execution speed penalty
The more compact the code (i.e. if you express the idea without addition "oh, how to avoid limitation Y of the language"), the better, because the code is much easier to maintain and it is harder to make a stupid (or worse) mistake.
There are no compelling stability or security reasons to switch. Shouldn't that be your boss's concern?

Would aspect oriented programming be a positive addition to the C# language?

I've had some interesting debates with colleagues about the merits if incorporating aspect oriented programming as a native paradigm to the C# language.
The debate seems to be divided into three camps:
Those folks who think that C# is already too complicated as it is, and another major feature like AOP would only muddy the waters further.
Those who think that it would be a great addition because anything that can increase the expressiveness of the language without breaking existing is a good thing.
Those who don't think it's necessary because libraries like PostSharp that perform post-compilation IL weaving already allow it in a language neutral way.
I'm curious what the community of C#/.NET developers out there think.
It would be great if languages would make it easier to develop and use AOP extensions.
For instance:
It would be nice if one could give a delegate (or anonymous method, or lambda) as a parameter to a custom attribute. It's not a lot of work to implement this in C#, it's quite easy to implement it in the CLR (since it supports types, why not methods?). And it would allow to express 'pointcuts' in an elegant way.
Support for 'fieldof' and 'methodof'. It is somewhat supported by the CLR (with bugs), not by C#. The same for 'eventof' and 'propertyof' (they have currently no support in the CLR).
Better debugging symbols could make it easier for an aspect weaver to report error messages and give the location in code.
It would be great to have a modular compiler; it would be less expensive to implement some features like source code generation based on aspects (for method and interface introductions).
That said, I don't think that the language should provide AOP extensions. This is too large (I think PostSharp 2.0 is more complex than the C# compiler itself, at least than C# 2.0). Let's face it: AOP is still rather experimental in the sense that we still don't know exactly what we want from it. There is still little experience. But we want the specification of a language to be stable and to address well-understood problems (imagine the Entity Framework were a part of the language).
Additionally, there are different ways to achieve AOP, and build-time is only one of them. There is nothing wrong in using runtime technologies, like JIT-emitted proxies (Spring/Castle); these are just for different use cases and have their own pros and cons.
So my opinion in one sentense: yes for limited and well-defined language extensions that make it easier to develop AOP frameworks; no for a full AOP implementation in the language.
I agree with the first camp. C# is already loaded with features. Leverage the PostSharp library instead.
It would be useful, but many of the uses are being included in various ways as it is. For example, we will have the ability to do post and pre validation in .NET4, which was one use for using around, in aspectJ.
By using extension methods you can inject new methods into objects you may not have source code for.
And, I don't believe it would be used much as C# developers seem to approach problems differently than Java programmers, which is easy to do since the two languages have diverged so much now.
I don't know if the companies that tend to use .NET would want to use something like AOP, and you would need tools to help understand what aspects are being injected where, such as AJDT on Eclipse.

Feasibility of shared code between .NET and Silverlight?

Having just gone through a small experimenting session to try to see how much work it would take to bring our .NET class library, or at least portions of it, into Silverlight so that we can reuse business logic between the two worlds, I'm wondering if others have experience with this sort of thing.
The things I noticed, off the top of my head:
Lots of attributes missing (Browsable(false) for instance)
Lots of interfaces missing, or present, but empty (ICloneable is hidden, ITypedList missing)
Reflection differences (everything reachable needs to be public)
Some base class differences (no Component?)
So I'm wondering, is it really feasible for me to even look at this as a possibility?
I got the initial code running, but I had to just comment out a whole lot of the base functionality, mostly around handling lists since they are based on ITypedList and some base classes. Apparently I need to change to ObservableCollection in Silverlight, so a whole of of base-code needs to be changed in order to cope.
The actual business test class I created is 99.5% identical to the one I would've made for .NET, only some minor changes that would easily be usable in .NET as well, just not as I would've made it before looking at Silverlight. In other words, it looks feasible to share business logic, provided I can make the base classes compatible.
Just so I'm clear, what I'm talking about is that I would basically have two project files, one for .NET, and one for Silverlight, but the actual C# source code would be the same, shared between the two.
So does anyone have any experience with this? Any tips or guidelines?
Will it be worth it? It certainly warrants more looking into.
It is definitely feasible.
It's done on a project here; the Silverlight project includes the C# ones, and there are some #IF statements handling some things (like log4net declarations), and other times things are just re-implemented. But in general, it's a huge win, and you should definitely attempt it (and certainly, we have, successfully).
-- Edit:
One point though, is that our OR/M (LLBLGen) didn't have inbuilt support for 'simple' objects to send down through Silverlight; but someone had written a plugin that handled it, which helped. So it may be worth considering what sort of DAL you're using, and how well it supports Silverlight.
What I've done to facilitate this is:
Frequent use of partial classes and #if !SILVERLIGHT to separate code into parts that Silverlight can handle.
Use of code generation whenever possible. For example I've been experimenting with T4 templates that generate Silverlight equivalent attributes (DisplayAttribute instead of DescriptionAttribute for example)
Whenever there's an interface/attribute that isn't implemented by Silverlight (such as IDeserializationCallback, ICloneable, INotifyPropertyChanging) I will create a dummy interface of the same name in the Silverlight application as long as I know that the fact that the implementation won't be used is not a problem.
Finally, it's worth noting that in Silverlight 4, the assembly format does allow for sharing of binaries between Silverlight and .NET as long as there are no dependencies that Silverlight does not support.
One more note about the separate base classes - it may be worthwhile to create an abstract class that derives from ObservableCollection in Silverlight and BindingList (or whatever you're using in .NET) to minimize the impact on your typed collections.
UPDATE
Today I was working on porting some .NET code to Silverlight that made heavy use of the System.Diagnostics API's like TraceSource, SourceSwitch, etc which do not exist in Silverlight. I created very minimal implementations of these in the Silverlight project and put them in the Einstein.Diagnostics namespace. In doing so I decided I needed a convention to easily identify code that was mimicking the .NET Framework vs. my own code. So I renamed the placeholder files to prefix them with an # sign. I also prefixed the class names in those files as well. The nice thing about that is that the # sign does not actually change their class names as far as the C# compiler is concerned. So #SourceSwitch still compiles to be Einstein.Diagnostics.SourceSwitch but in the code I can easily see something is up. I've also decorated these classes with a [SilverlightPlaceholder] attribute.
I do this with protobuf-net, and I use a few approaches:
conditional compilation symbols in the project file to trigger subtle code-branches (yes, it isn't perfect, but it works)
re-introduction of some things; attributes might be an example here - your code can still use re-introduced attributes, even if the framework code doesn't; as a more extreme example of this, for compact framework I had to re-introduce a good chunk of the Expression API, which was fun
just drop some things ;-p
However if you are using ITypedList (which you mention), I can see that whole approach falling apart pretty messily; component-model is complex enough already, without having to force your way through the hacks too. It really depends quite how far you've gone down this road. Maybe 4.0 / dynamic will open up some of these options again?
One possible fix to your issue is to copy the missing code from the Mono project. Back in the day, I did a small project with the Compact Framework and it was missing the entire System.XLM namespace. I just copied the entire thing from Mono into my project, compiled it and it worked great with minimal changes, iirc.

Upgrading Code from .Net 1.1 to 2.0/3.5 (C#)

I am upgrading a Windows Client application that was earlier .NET 1.1. The previous developer handwrote many solutions that can be done automatically with the newer versions of .NET. Since I am relatively fresh to .NET and do not have the complete overview of the features I am asking here.
What is the most notable classes and syntax features provided in later .NET versions that is likely to swap out handwritten code with features from the library?
Biggest changes off the top of my head:
Use generic collections instead of ArrayList, Hashtable etc.
For C# 3.5, use LINQ instead of manually filtering/projecting
Use generic delegates instead of having to declare your own all the time
Use anonymous methods instead of creating a one line method used to create a delegate in one place
Use BackgroundWorker for WinForms background tasks
Generics is the most wide-reaching change in my view.
Personally, I would leave any 1.1 code that works fine when compiled with 2.0/3.5. Unless you have the time, anything you rewrite you'll have to test again, and you still may introduce new bugs that your testing can't find.
Things that I'd look to use for future versions though, would be generics and LINQ. Generics with .NET 2, and LINQ with .NET 3.5.
LINQ was a big leap. Might be possible to use that in some places (e.g. XML code). Also, generics may reduce the need for some classes.
Also be aware of and test for possible impact of breaking changes between the versions of the framework. A google search should reveal the top issues.

Conversion to .Net 3.5

I recently started maintaining a .Net 1.1 project and would like to
convert it to .Net 3.5.
Any tips to share on reducing code by making use of new features?
As a first attempt, I would like to convert a bunch of static helper functions.
Update: The main reason why I am converting is to learn new features like static classes, LINQ etc. Just for my own use at least for now.
I would suggest starting by migrating to .NET 2.0 features, first.
My first step would be to slowly refactor to move all the collections to generic collections. This will help tremendously, and ease the migration into the .NET 3.5 features, especially with LINQ. It should also have a nice impact on your performance, since any collections of value types will perform better.
Be wary in this of converting HashTables to Dictionary<T,U>, since the behavior is different in some cases, but otherwise, ArrayList->List<T>, etc are easy, useful conversions.
After that, moving helpers to static classes, and potentially extension methods, would be a good next step to consider. This can make the code more readable.
You can use static classes (C# 2.0 feature) to rewrite old helper functions.
If you can swing it, the easiest way I've found to do this is using Visual Studio 2008 and ReSharper. ReSharper will show you, via some kindly visible notation, where you can improve your code. Then it will show you a keyboard shortcut Alt+Enter to "fix" your code.
ReSharper also has a feature called "Cleanup Code" that will will do some of the refactoring for you.
Why convert at all, .Net 1.1 is fully compatible with .Net 3.5, so you should not find any breaking changes when you migrate. If you need to refactor an area because it has problems or you wish to extend it somehow then I would consider migrating to use newer features, but otherwise why touch it and risk breaking it?
Edit As this is a learning excercise rather than changing production code I'd revise my views somewhat; this is probably a good way to learn new approaches. I'd certainly look at LINQ. In places where the old code was iterating through lists or manipulating XML or data from a DB see if you can re-write using LINQ instead.
If you want to start by "convert[ing] a bunch of static helper functions", then you'll want to check out extension methods.
It's likely that you can use them to make your code simpler and more readable.

Categories