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

REFL003 incorrectly assumes that .GetType() returns only the type seen at compile-time #183

Open
jnm2 opened this issue Nov 3, 2018 · 3 comments

Comments

@jnm2
Copy link
Collaborator

jnm2 commented Nov 3, 2018

0.1.16-dev

void M(IEnumerable<object> objectImplementingIEnumerable)
{
    objectImplementingIEnumerable.GetType().GetMethod("Add");
}

REFL003 The type System.Collections.Generic.IEnumerable<object> does not have a member named Add.

The analyzer should bail if it sees a GetType() on an expression of a virtual type since it can know nothing about the expected concrete type which may be internal to an external lib.

Additionally, if it sees a GetType() on a nonvirtual type, maybe it should bail anyway because it will be reporting #169 in all these cases anyway.


Actual code, in case you wonder why you would do this:

        public static IReadOnlyCollection<Assembly> GetAssemblies(this ITypeDiscoveryService typeDiscoveryService)
        {
            var serviceType = typeDiscoveryService.GetType();
            if (serviceType.FullName == "Microsoft.VisualStudio.Design.VSTypeResolutionService") // Achieve instantaneous load, vs around a second's freeze
            {
                var normalEntries = (IEnumerable<object>)serviceType.GetField("_normalEntries", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(typeDiscoveryService);
                // ...
@JohanLarsson
Copy link
Collaborator

We should at least change it to warn REFL009. Maybe REFL009 should be default info?

@jnm2 jnm2 changed the title REFL003 incorrectly assumesthat .GetType() returns only the type seen at compile-time REFL003 incorrectly assumes that .GetType() returns only the type seen at compile-time Nov 3, 2018
@jnm2
Copy link
Collaborator Author

jnm2 commented Nov 3, 2018

Another problem that will be resolved once GetType bails when it can't prove the concrete type:

obj.GetType().Assembly.GetType("Foo")

REFL037 The type does not exist

Yes it does; I've just checked obj.GetType().FullName.

@jnm2
Copy link
Collaborator Author

jnm2 commented Mar 25, 2020

REFL009 would be fine, but I would probably disable it because it says more about the IDE's metadata settings and the limitations of static analysis than about the types I'm using.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants