Skip to content
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

Generic [Try]LookupMember<T> overloads #392

Closed
Washi1337 opened this issue Dec 22, 2022 · 1 comment · Fixed by #402
Closed

Generic [Try]LookupMember<T> overloads #392

Washi1337 opened this issue Dec 22, 2022 · 1 comment · Fixed by #402
Labels
dotnet Issues related to AsmResolver.DotNet enhancement
Milestone

Comments

@Washi1337
Copy link
Owner

Problem Description

Currently, ModuleDefinition.LookupMember is a very generic function that returns a IMetadataMember when the call is successful. If the type of the member is already known (e.g., because the provided metadata token has a known table index), this often requires extra type-casts or type-checks at the call-site. This can make code less readable / concise:

var type = (TypeDefinition) module.LookupMember(token);
if (module.TryLookupMember(token, out var member) && member is TypeDefinition type) 
{
   /* ... Use `type`  ...*
}

Proposal

Add generic overloads LookupMember<T>(MetadataToken) and TryLookupMember<T>(MetadataToken, out T), that also try to cast the resolved member to the specified type parameter, such that the type inference of the C# compiler can take over, replacing the explicit or safe type-casts:

var type = module.LookupMember<TypeDefinition>(token);
if (module.TryLookupMember(token, out TypeDefinition type)) 
{
   /* ... Use `type`  ...*
}

Alternatives

C# Pattern matching is pretty decent nowadays and could be combined with the original versions of LookupMember, but this still is not as concise as it could be.

Additional Context

This is extra nice if it is used in a chain of calls, avoiding many parentheses. For example:

var cctor = ((TypeDefinition) module.LookupMember(token))
    .Methods.First(m => m.IsConstructor && m.IsStatic);

versus:

var cctor = module.LookupMember<TypeDefinition>(token)
    .Methods.First(m => m.IsConstructor && m.IsStatic);
@Washi1337 Washi1337 added enhancement dotnet Issues related to AsmResolver.DotNet labels Dec 22, 2022
@sunnamed434
Copy link
Contributor

Oh, yeah, I do like it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
dotnet Issues related to AsmResolver.DotNet enhancement
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants