SoFunction
Updated on 2025-03-07

Introduction to C# conditional compilation, inline functions, and CLS

1. Conditional Compilation

#ifConditional compilation hides non-conditional (#else if) code, and we may ignore this part of the code in development. When we switch conditional constants to this part of the code, an error may be reported due to various reasons.

If you use features for conditional compilation marks, you can pay attention to this part of the code during development.

[Conditional("DEBUG")]

For example, when using Modify all references - modify a class member variable or static variable name,#ifThe code in non-conditions will not be modified because this part of the code is "invalid", and it is used[Conditional("DEBUG")]The code of  has nothing to do with the conditions and will be modified synchronously.

ConditionalThe method of feature tagging, etc., remains valid during development and may be excluded when compiled.

Code snippets can only be used#if, if it is a single method, you can useConditional 。

2. MethodImpl Features

This feature is in the namespace, specifying details about how to implement the method.

You can refer to the usage method of inline functions.https:///article/

The MethodImpl feature can affect the behavior of the JIT compiler.

not availableTo obtain information about this feature, that is, it cannot be obtained through the method of obtaining the feature.MethodImplRelevant information (reflection), can only be called()or ()Come to search.

MethodImpl can be used on methods and constructors.

MethodImplOptions is used to set compilation behavior. Enum values ​​can be used in combination. The enumeration description is as follows:

enumerate Enumeration values illustrate
AggressiveInlining 256 This method should be inlined if possible.
AggressiveOptimization 512 This method contains a thermal path and should be optimized.
ForwardRef 16 The method has been declared, but implementation is provided elsewhere.
InternalCall 4096 This call is an internal call, that is, it calls a method implemented in the common language runtime.
NoInlining 8 This method cannot be an inline method. Inline is an optimization method in which method calls are replaced with a method body.
NoOptimization 64 When debugging possible code generation issues, this method is not optimized by a real-time (JIT) compiler or native code generation (see)。
PreserveSig 128 Signature exactly according to the declaration export method.
Synchronized 32 This method can only be executed on one thread at a time. Static methods are locked on type, while instance methods are locked on instances. There is only one thread that can be executed in any instance function, and only one thread that can be executed in any static function of any class.
Unmanaged 4 This method is implemented in unmanaged code.

SynchronizedThe modified method can avoid some problems in multithreading, but it is not recommended to use locked instances or locks on types for public types, becauseSynchronizedYou can lock public types and instances of code that are not your own. This can cause deadlocks or other synchronization issues.

Meaning, if the shared member has set a lock, it should no longer be inSynchronizedUsed in the method, such that double locking can easily lead to deadlocks and other problems.

3、CLSCompliantAttribute

Indicates whether the program element complies with the Common Language Specification (CLS).

CLS specifications can be referenced:

/en-us/dotnet/standard/language-independence

Global enable method:

Add a file in the program directory, or open the obj directory and find the ending file, such as .NETCoreApp,Version=v3., add:

using System;	// If you already have this line, don't add it[assembly: CLSCompliant(true)]

It can be used in the code afterwards[CLSCompliant(true)]Features.

Locally open:

It can also be used on class and other members:

[assembly: CLSCompliant(true)]

You can apply attributes to the following program elements of CLSCompliantAttribute: assembly, module, class, structure, enumeration, constructor, method, attribute, field, event, interface, delegate, parameters, and return values. However, the concept of CLS compliance applies only to members of assemblies, modules, types, and types.

When compiling the program, it will not check whether the code complies with the CLS requirements by default, but if yours can be public (code sharing, Nuget publishing, etc.), it is recommended to use it.[assembly: CLSCompliant(true)], indicate that your library complies with CLS requirements.

High-quality code is particularly important in team development and when sharing code internally, so it is necessary to use tools to check the code, such as roslyn static analysis, sonar scanning, etc. You can also use the above features to automatically use CLS inspection.

CLS Partial Requirements:

  • Unsigned types should not be part of the public interface of the class (available by private members), such as UInt32, which are of C#, but are not in the CLS "standard".

  • Unsafe types such as pointers cannot be used with public members, even if unsafe code should not be used in public methods. (Private members can use).

  • Class names and member names should not be duplicated. Although case sensitive in C#, CLS does not recommend non-overloaded functions with the same name, such as MYTEST and Mytest.

  • Only attributes and methods can be overloaded, operators should not be overloaded. Overloading operators can easily cause program errors when the caller is unaware of it, and it is very difficult to troubleshoot problems with overloading operators.

We can compile the following code and try usingCLSCompliant :

[assembly: CLSCompliant(true)]
[CLSCompliant(true)]
public class Test
{
    public void MyMethod()
    {
    }
    public void MYMETHOD()
    {
    }
}

Warning in the IDE: warning CS3005: Only the identifier "()" with different upper and lower case does not conform to CLS, and Warn will also be prompted during compilation. Of course, compilation will not be prevented and the program will not be affected.

In short, if you want to mark an assembly CLS specification, you can use[assembly: CLSCompliant(true)]Features.

[CLSCompliant(true)]The feature indicates that this element complies with the CLS specification. At this time, the compiler or IDE will check your code to check whether it really complies with the specification.

If you want to write code that does not meet the specifications, you can use[CLSCompliant(false)]

4. Customize type alias if necessary

C# can also define type alias.

using intbyte = System.Int32;
using intkb = System.Int32;
using intmb = System.Int32;
using intgb = System.Int32;
using inttb = System.Int32;
        byte[] fileByte = ("./");
        intmb size =  / 1024;

In some cases, using alias can improve code readability. Don't use the above code for real projects. I'm just writing an example, which is not a suitable application scenario.

This is all about this article about C# conditional compilation, inline functions, and CLS. I hope it will be helpful to everyone's learning and I hope everyone will support me more.