Skip to content

Commit 027ae25

Browse files
committed
Introduced TryAdd()
When adding a type, it is conceivable that a class being derived from has already added that type. For this reason, most derivatives of `StaticTypeLookupService` implement local checks to avoid a key conflict. Since this is such a common scenario, that logic is being centralized as a `TryAdd()` method. This method will add the `Type` if no `Type` with the same key exists. Otherwise, it will simply return `false`, instead of throwing an exception. If an exception is preferred in this scenario, the existing `Add()` method will satisfy that condition. This complements the newly added `AddOrReplace()` method, which will replace the existing `Type` if it exists (cd92791).
1 parent cd92791 commit 027ae25

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

OnTopic/StaticTypeLookupService.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,22 @@ public StaticTypeLookupService(
9595
/// </summary>
9696
protected void Add(Type type) => _typeCollection.Add(type);
9797

98+
/*==========================================================================================================================
99+
| METHOD: TRY ADD
100+
\-------------------------------------------------------------------------------------------------------------------------*/
101+
/// <summary>
102+
/// Determines if a <see cref="Type"/> with the given <see cref="MemberInfo.Name"/> exists. If it does, returns <c>false
103+
/// </c>; otherwise, adds the <see cref="Type"/> and returns <c>true</c>.
104+
/// </summary>
105+
protected bool TryAdd(Type type) {
106+
Contract.Requires(type, nameof(type));
107+
if (Contains(type.Name)) {
108+
return false;
109+
}
110+
Add(type);
111+
return true;
112+
}
113+
98114
/*==========================================================================================================================
99115
| METHOD: ADD OR REPLACE
100116
\-------------------------------------------------------------------------------------------------------------------------*/

0 commit comments

Comments
 (0)