## Why is this an issue?

The `Trace.WriteLineIf` Method from the `System.Diagnostic.Trace` facility writes a trace if the condition passed as the first parameter is `true`.

`TraceSwitch` allows trace control via `bool` properties for each relevant `TraceLevel`, such as `TraceSwitch.TraceError`.

Using `Trace.WriteLineIf` with such properties should be avoided since it can lead to misinterpretation and produce confusion.

In particular, `Trace.WriteLineIf` may appear as equivalent to the level-specific tracing methods provided by `Trace`, such as `Trace.Error`, but it is not.

The difference is that `Trace.WriteLineIf(switch.TraceError, …​)` conditionally writes the trace, based on the switch, whereas `Trace.TraceError` always writes the trace, no matter whether `switch.TraceError` is `true` or `false`.

Moreover, unlike `Trace.TraceError`, `Trace.WriteLineIf(switch.TraceError, …​)` would behave like `Trace.WriteLine(…​)` when `switch.TraceError` is `true`, writing unfiltered to the underlying trace listeners and not categorizing the log entry by level, as described more in detail in {rule:csharpsquid:S6670}.

## How to fix it

The fix depends on the intent behind the use of `TraceSwitch` levels with `Trace.WriteLineIf`.

If it is trace categorization, level-specific tracing methods, such as `Trace.TraceError` or `Trace.TraceWarning`, should be used instead.

If it is trace filtering, `TraceSource` should be used instead.

If it is log filtering, `Trace` should be replaced by logging APIs, such as the `ILogger` API.

Modern logging APIs are also more suitable than `Trace` when high-performance logging is required.

## Resources

### Documentation

- Microsoft Learn - `Trace.WriteLineIf` Method
- Microsoft Learn - `TraceSwitch`
- Microsoft Learn - `TraceSource`
- Microsoft Learn - `Trace.WriteLine` Method
- Microsoft Learn - High-performance logging in .NET

### Articles & blog posts

- StackOverflow - Difference between Trace.WriteLineIf and Trace.Error
- StackOverflow - Difference between TraceSwitch and SourceSwitch
- InfoSupport Blogs - Please be careful when using Trace.WriteLineIf()