Skip to content

Make len work for ICollection<> interface objects #1253

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ details about the cause of the failure
- Fix non-delegate types incorrectly appearing as callable.
- Indexers can now be used with interface objects
- Fixed a bug where indexers could not be used if they were inherited
- Made it possible to use `__len__` also on `ICollection<>` interface objects

## [2.5.0][] - 2020-06-14

Expand Down
6 changes: 5 additions & 1 deletion src/runtime/slots/mp_length.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public static MethodInfo Method
}
}

public static bool CanAssgin(Type clrType)
public static bool CanAssign(Type clrType)
{
if (typeof(ICollection).IsAssignableFrom(clrType))
{
Expand All @@ -36,6 +36,10 @@ public static bool CanAssgin(Type clrType)
{
return true;
}
if (clrType.IsInterface && clrType.IsGenericType && clrType.GetGenericTypeDefinition() == typeof(ICollection<>))
{
return true;
}
return false;
}

Expand Down
2 changes: 1 addition & 1 deletion src/runtime/typemanager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ internal static IntPtr CreateType(ManagedType impl, Type clrType)
InitializeSlots(type, impl.GetType(), slotsHolder);

if (Marshal.ReadIntPtr(type, TypeOffset.mp_length) == IntPtr.Zero
&& mp_length_slot.CanAssgin(clrType))
&& mp_length_slot.CanAssign(clrType))
{
InitializeSlot(type, TypeOffset.mp_length, mp_length_slot.Method, slotsHolder);
}
Expand Down
14 changes: 14 additions & 0 deletions src/tests/test_mp_length.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,17 @@ def test_custom_generic_collection_explicit___len__():
s.Add(1)
s.Add(10)
assert len(s) == 2

def test_len_through_interface_generic():
"""Test __len__ for ICollection<T>"""
import System.Collections.Generic
l = System.Collections.Generic.List[int]()
coll = System.Collections.Generic.ICollection[int](l)
assert len(coll) == 0

def test_len_through_interface():
"""Test __len__ for ICollection"""
import System.Collections
l = System.Collections.ArrayList()
coll = System.Collections.ICollection(l)
assert len(coll) == 0