I'm currently tempted to write the following:
public class Class1()
{
public Class1()
{
MyProperty = new Class2(this);
}
public Class2 MyProperty { get; private set; }
}
public class Class2()
{
public Class2(Class1 class1)
{
ParentClass1 = class1;
}
public Class1 ParentClass1 { get; set; }
}
Is passing "this" as an argument a sign of a design problem? What would be a better approach?
This is not a bad thing. In fact, it is a very good thing. Passing functions into functions is so important to programming that we invented lambda functions as a shorthand.
Passing value objects by reference is in general a bad design. There are certain scenarios it's valid for, like array position swapping for high performance sorting operations. There are very few reasons you should need this functionality. In C# the usage of the OUT keyword is generally a shortcoming in and of itself.
No, there's no fundamental design problem with passing this
. Obviously, this can be misused (creating coupling that's too tight by having a related class depend on values stored in your instance when values of its own would be called for, for example), but there's no general problem with it.
no it is not a problem. THats why 'this' keyword exists, to allow you to pass yourself around
It's hard to say from what you've posted. The question you should ask yourself is: why does class2 need to know about class1? What types of operations is class2 going to perform on class1 during its lifetime, and is there a better way to implement that relationship?
There are valid reasons for doing this, but it depends on the actual classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With