Home Dashboard Directory Help
Search

C# - Conditional Compilation based on availability of a type by Brad Robinson (Cognethos)


Status: 

Closed
 as Other Help for as Other


10
4
Sign in
to vote
Type: Suggestion
ID: 679124
Opened: 7/11/2011 7:53:24 PM
Access Restriction: Public
1
Workaround(s)
view

Description

Suggestion: it would be great if C# could conditionally include/exclude code based on the availability of a type:

     #if typeof(System.Web.HttpContext)

     // Optional code that requires System.Web

     #endif


Currently there is no mechanism for conditional compilation in C# based on the target platform. Rather than requiring a specific platform however, sometimes its a feature available in some platforms that's required.

For example, suppose a particular build of a library has extra features if the DLR is available. Rather than checking .NET40, why not conditionally include it like this:

    #if typeof(System.Dynamic.DynamicObject)
    #endif

This would also be useful for code distributed as source rather than an assembly (as is sometimes the case with NuGet now - see Massive, PetaPoco and Dapper for example) where one wants to conditionally include code depending on the target project's referenced assemblies.

For example, as the developer of PetaPoco (a micro ORM) I would like to be able to optionally include better support for SQL Server geography types - but only if the target project has an assembly reference to those types.
Details
Sign in to post a comment.
Posted by Microsoft on 2/15/2013 at 2:49 PM
Thanks for your suggestion!

As we've added more and more platforms, having code that varies behavior depending on the target has become more and more of a scenario.

We are currently looking at different ways of addressing this. I can't share details, but the eventual solution is likely to be different from what you propose. Nevertheless, thanks for adding your vote to the scenario.

Thanks again,

Mads Torgersen, C# Language PM
Posted by ddboarm on 8/1/2012 at 1:08 PM
I would be happy with the ability to define WIN64/WIN32 without the need to provide multiple assemblies targeting specific platforms - x86, etc.
Posted by Microsoft on 7/11/2011 at 8:13 PM
Thank you for your feedback, we are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(http://support.microsoft.com)
Sign in to post a workaround.
Posted by Terry L. Lewis on 4/12/2012 at 11:01 AM
I've managed to deal with the exact scenario given in the first example by using dependency injection. Unfortunately, if the type in question has no explicit interface defined, then we are forced to create our own interface to meet our needs, and then wrap the object in question with a custom implementation of that interface.

Occasionally, this is actually the better way to work. At times, it can be a real pain.