views:

173

answers:

2

Is it possible to create a library that can be consumed from .Net 2.0 and also allows .Net 3.0+ consumers to benefit from DataContracts if they wish?

I don't see any technical obstacle for this other than the library that contains the different DataContract related attributes is a .Net 3.0 library. Can these attributes be implemented manually in similar way as ExtensionMethodAttribute?

A: 

Since .NET 2.0 and .NET 3.0 and 3.5 use the same CLR (2.0), you shouldn't have any difficulties.

Andrew Hare
What happens if a .Net 2.0 client running on a computer that doesn't have .Net 3.0 installed tries to read the attributes? I don't have such a client currently so I cannot test this.
Mikko Rantanen
Would the attributes inherit from a base class or implement an interface that only exists in .NET 3.0? If not you should be ok.
Andrew Hare
The DataContractAttribute and such ARE a class that exists only in .Net 3.0.
Mikko Rantanen
Good point :) Please see Joe's answer for what this means.
Andrew Hare
+1  A: 

If you add .NET 3.0 attributes to an assembly, then run this on a machine with .NET 2.0 only, this amounts to having an attribute on your code from an assembly that is unavailable at runtime.

This will mostly work fine as long as the .NET 2.0 application doesn't actually attempt to read the attributes. For example, the following code will throw a FileNotFoundException because it will fail to load System.ServiceModel.dll if run on a machine with .NET 2.0:

[ServiceContract] // Attribute from System.ServiceModel.dll
class MyClass
{
  ...
}
...
    // this will throw a FileNotFoundException if System.ServiceModel.dll is not available
    object[] attributes = typeof(MyClass).GetCustomAttributes(false);

Therefore if you don't know who will be consuming your class library, you can't guarantee 100% that you won't break them.

The above can be avoided by shipping a copy of System.ServiceModel.dll (or other assembly containing attributes you're using) with your application, or (I think) by using the overload of GetCustomAttributes that takes a System.Type argument, so you only read attributes that are known to be available.

Joe