4

In C# is it ok to use this in the constructor? (i.e., is it ok to reference the instance in the constructor)

As a simple example:

public class Test{

 public Test()
 {
    Type type = this.GetType()
 }

}
1

2 Answers 2

5

Yes, you can use this in the constructor, but not in field initializers.

So this is not valid:

class Foo
{
    private int _bar = this.GetBar();

    int GetBar()
    {
        return 42;
    }
}

But this is allowed:

class Foo
{
    private int _bar;

    public Foo()
    {
        _bar = this.GetBar();
    }

    int GetBar()
    {
        return 42;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Are you looking for something like this?

public class Test{

 private string strName;
 public Test(string strName)
 {
    this.strName = strName;
 }

}

I think is good to use in every part of the class the this identifier... Atributes, Methods, Properties, because it gets more allusive to what you are modifying or using, in complex classes or large ones it helps you to know faster what you are using, but as I said, in my point of view.

4 Comments

this is just extra verbosity with no added value to me, but to each their own.
yes its just allusive like other reserved words like const, readonly, just for the programmer, well and in my example, it is forcely needed when you use a parameter named exactly equal to a global property/attribute, and you dont get confused if you are using a local variable, a paremeter or a global variable with the 'this'.. but as you said to each their own
I avoid that with an underscore for member variables. I do not like the memberVariable convention just for that reason. Then I get collisions in method signatures and have to use this all over the place. Also, I don't think you mean to say "Allusive". Explicit perhaps? :)
hehe, yeps maybe xD. And you said it, you can get collisions in methods if you dont use it, I think for not having future problems, just use it, it doesn't hurt you a lot, just like 5 characters this. xD

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.