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

Null reference exception when using the "new" keyword with properties #1216

Closed
howcheng opened this issue Nov 5, 2021 · 1 comment
Closed

Comments

@howcheng
Copy link

howcheng commented Nov 5, 2021

Several months ago, I reported #1175 and I think this may be related because it again involves subtyping with the use of the "new" keyword.

I have an interface (IRepository<T>) that defines a property (Foo Foo { get; set;}), and then a derived interface (IRepository<T, TK>) that redefines that property (Foo<T>). Next, I have a Service<T> class which takes a IRepository<T> in its constructor and sets its own Foo property from the repository property, then a derived Service<T, TK> class which takes a IRepository<T, TK> in its constructor and passes it to the base.

When creating a new instance of the Service<T, TK> class using a mocked IRepository<T, TK>, the Foo property is null, presumably the setter in the base class constructor uses the base interface's property definition, which is of type Foo and not Foo<T>.

Here is a fiddle that demonstrates the issue: https://dotnetfiddle.net/SDY3JZ

When using actual concrete classes, this all works fine, it's just the mock that has problems.

Thanks.

@howcheng
Copy link
Author

I recently learned about the .As<>() method, so it turns out I was just doing the setup for the mock incorrectly.

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

1 participant