简体   繁体   中英

What is the right string comparison value to be used in a machine to machine communication scenario?

Consider a scenario where you are implementing code meant to be used for machine to machine communication. The typical example for that is the code executed inside a web API action method.

Suppose that you want to perform an exact match between strings; maybe you have a list of users and you wan to find one specific user provided the user name:

List<User> users = ....
const string username = "user-123";
var user = users.Find(u => string.Equals(username, u.UserName));

In such a scneario should I use StringComparison.Ordinal or StringComparison.InvariantCulture ?

Based on my understanding, since I want to perform an exact match between two strings, the proper choice here is StringComparison.Ordinal .

The typical example for culture sensitive comparison between the two strings Straße and strasse , where the two strings are considered equal due to linguistical rules, does not seem to fit here.

Is this assumption correct?

If this is correct, can you provide an example where using the invariant culture instead of the ordinal comparison is the right choice?

Just to clarify, I'm asking because I'm working on a code base where there are plenty of string comparisons using the invariant culture. Many of these cases refer to exact string match performed in a machine to machine communication scenario . So I want to be sure to clearly understand the rationale behind the right choice of a string comparison value.

It would seem from the details provided that you are correct in your assumption - you want to find a specific user where the name is "Bob". "Bób" is a different user and should not match, ie you are actually trying to match two symbols, and not how the username would be read.

If, however, you were looking up street names, you may want to ask the code to consider "strasse" and "Straße" to be considered as the same, as you are doing a linguistic match ie would the client read these two things in the same way.

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