Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad practice to pass "this" as an argument?

Tags:

c#

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?

like image 740
Adam Lear Avatar asked Mar 16 '10 16:03

Adam Lear


People also ask

Is it bad practice to pass function as parameter?

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.

Is it bad practice to pass by reference?

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.


3 Answers

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.

like image 152
Adam Robinson Avatar answered Oct 03 '22 02:10

Adam Robinson


no it is not a problem. THats why 'this' keyword exists, to allow you to pass yourself around

like image 21
pm100 Avatar answered Oct 01 '22 02:10

pm100


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.

like image 8
Joe Avatar answered Sep 29 '22 02:09

Joe