C #: using this in constructor

In C # is it ok to use this in the constructor? (that is, is it normal to refer to an instance in the constructor)

As a simple example:

public class Test{ public Test() { Type type = this.GetType() } } 
+4
source share
2 answers

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

So this is not true:

 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; } } 
+5
source

Are you looking for something like this?

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

I think it’s useful to use this identifier in every part of the class ... Attributes, Methods, Properties, as it becomes more attractive for what you modify or use, in complex classes or large, it helps you better know what you are using but, as I said, from my point of view.

+1
source

Source: https://habr.com/ru/post/1379744/


All Articles