1

I occasionally find myself passing this or Me to a child object. Such as this condensed real-world example...

Public Class Entity

    Private mValidator as New EntityValidator()

    Readonly Property IsValid()
        Return mValidator.Validate(Me)
    End Property

End Class

I'm concerned about .Validate(Me). I get no warnings or Code Analysis violations, but it just feels wrong. I get nervous about infinite recursion and garbage collection.

We have memory leaks on a project and I've wondered if it was due to this. I've never been able to find any resource that addresses the issue.

Is this practice OK, or is my paranoia deserved?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
mr_plum
  • 2,448
  • 1
  • 18
  • 31
  • 1
    I agree with @JSWork: we may be missing some bit of code that sets properties on the EntityValidator that would justify Validate() not being static, but all else being equal, it should be a static method, which would not even require an instance in the first place. – Dave C Nov 08 '11 at 19:53
  • Are you saying to make EntityValidator.Validate() static and my code to read Return EntityValidator.Validate(Me)? – mr_plum Nov 08 '11 at 20:01
  • No, I think they are saying that your snippet doesn't give enough information. There's no clue in your code why EntityValidator would need to keep a reference. It looks like you pass in `Me`, it's validated, and the object `Me` is not stored in the object `mValidator` (but even if it were, there shouldn't be a problem). – Abel Nov 08 '11 at 20:09

2 Answers2

3

This will not, by itself, cause a memory leak, and there is nothing inherently wrong with passing this to another object. However, I would be wary of circumstances where the second object actually retains a reference to the passed-in object, as circular references can, in general, cause problems with understandability and maintainability.

Dave C
  • 429
  • 3
  • 9
1

Circular references are allowed in VB and in C#. A reference is essentially little more than a value of the size of a machine WORD in memory. If there's an object A and B, and if A points to B and B points to A, then A internally just holds a value that points to the actual object B and B just has a value that points to the actual object of A.

Someone else explains circular references better than I can, try this thread, about circular references and check the first answer. But in short: no, they won't harm your program and they are allowed and valid, even common.

If you want to find out where your memory leak is coming from, try memory profiling.

Community
  • 1
  • 1
Abel
  • 56,041
  • 24
  • 146
  • 247
  • @nuzabar: What makes you think you have a memory leak? How much do you know about Garbage Collection? – JSWork Nov 08 '11 at 21:57