Reputation: 170489
In my code, I want to check if a specific assembly is loaded. I have this code:
var assembly = AppDomain.CurrentDomain
.GetAssemblies()
.Where(a => a.FullName.StartsWith("Microsoft.WindowsAzure.ServiceRuntime"))
.SingleOrDefault();
Now, this code relies on specific capitalization of the assembly – the comparison is case-sensitive.
Do I need the comparison to be case-insensitive or can I expect the specific capitalization at all times?
Upvotes: 1
Views: 596
Reputation: 13551
The docs acknowledge inconsistencies in the case sensitivity of assembly names and they recommend comparing them case-sensitively:
The runtime treats assembly names as case-insensitive when binding to an assembly, but preserves whatever case is used in an assembly name. Several tools in the Windows SDK handle assembly names as case-sensitive. For best results, manage assembly names as though they were case-sensitive. -- https://learn.microsoft.com/dotnet/standard/assembly/names
Yet, if you choose to compare the name of the assembly (essentially AssemblyName.Name
) case-insensitively, it is not clear whether to compare ordinally or using the invariant culture. I would prefer ordinal comparison in such technical contexts, i.e. StringComparer.OrdinalIgnoreCase
and StringComparison.OrdinalIgnoreCase
. As the best practices for comparing strings advise:
Use the non-linguistic StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase values instead of string operations based on CultureInfo.InvariantCulture when the comparison is linguistically irrelevant (symbolic, for example).
Upvotes: 0
Reputation: 8408
According to this, the runtime treats assembly names as case-insenstive. That is, you won't have two assemblies loaded at the same time with names that only differ in their capitalization.
So, if you ONLY want to check for a specific assembly name you should do a case-insensitive comparison using this overload of StartsWith with StringComparison .InvariantCultureIgnoreCase
to avoid the (very rare) case where the capitalization of an assembly name has changed.
a.FullName.StartsWith("Microsoft.WindowsAzure.ServiceRuntime",
StringComparison.InvariantCultureIgnoreCase)
Upvotes: 3