简体   繁体   中英

Can you add a preprocessor directive for a C# version?

Is there a way to add a preprocessor directive that compares the C# version used by the compiler?

For example :

public T MyMethod<T>()
{
#if CS_7
    return default; // Feature 'default literal' is not available in C# 7.0. Please use 7.1 or greater.
#else
    return null; // Ignore the fact that this won't work, it isn't the point of the question
#endif
}

Would the .NET version be the way to go here? Wouldn't there be situations where the compiler used is different for the same project? (ie if different employess use different versions of Visual Studio)

Apparently you can't, but the C# version used depends on the framework version ( list of version per framework ) used in the project, which provides a default C# version, unless configured otherwise manually through something like the property (see linked documentation).

Thus, most situations where you would want a C# version preprocessor directive can either be resolved by adding a framework preprocessor directive or forcing a specific C# version in the project itself using the property in the project file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM