My team is building some new awesomeness for Visual Studio and having fun conversations along the way. Here is the latest thing we are tossing about and we would like your help in thinking it through.
A given class may be referenced many ways in code. Not all of those ways are things we think of as a reference, though. When you consider the below examples, ask yourself, is this a reference?
What do I mean by ?Is this a reference?? Pretend I have tooltip or some tool that shows me ?references? to my class. Does the example in each case increment the reference counter? Consider this in terms of what is in your mental model of the code, not what is in the IL. I want to know how you think about it, not the compiler.
Case 1 : Simple Reference
In this case, the reference count of class Foo is obviously 1.
public class Foo { } public class Bar { Foo foo = new Foo(); }
Case 2 : Derivation
When a class inherits from another, does that increment the counter?
public class Foo { } public class Bar : Foo { }
Case 3 : Internal Derivation
Does it matter when the derivation is internal to the class being referenced?
public class Foo { public class Bar : Foo { } }
Case 4 : Initialization
Does this increase the reference counter for class Foo() to one or two? Remember I am wondering about what?s in your mental model, not what the IL does physically.
public class Foo { public int X = 0; } public class Bar { static readonly Foo _foo = new Foo(); void Goo() { _foo.X += 1; } }
Case 5 : Initialization Revisited
(Updated)
Has class Foo been referenced one or two times below?
public class Foo { } public class Bar { Foo _foo; void Goo() { _foo = new Foo(); } }
How about now? Is the count the same or different as the above example?
public class Foo { } public class Bar { Foo _foo = new Foo(); }
How ReSharper Does It
This is the configuration dialogue for ResSharper?s ?Find Usages ? Advanced? feature. Note I am showing the default settings.
A coworker and I agree: Y, Y, N, 1, 2, 1
Good examples! But you are just scratching the surface of this difficult problem. For example, here’s a whole new dimension to consider:
using ABC = Foo;
class Bar : ABC {}
How many references to Foo are in that program fragment?
Thanks to you, the answer is 2. At least that what you returned 🙂
Good. Thank you!
case1: 1, obviously
case2: Y, you’re looking for where Foo is referenced yes?
case3: N, Same as case2
case4: 1, you can’t remove the 1st reference without busting things, so it’s one.
case5: 1 and 1, same as case4