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()
}
}
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()
}
}
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;
}
}
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.
this is just extra verbosity with no added value to me, but to each their own.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? :)