Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use this. to access internal class members?

On the internet I see a lot of code which uses this. to access local members of a class, like this:

private String _whatever;
public String Whatever
{
  get
  {
    return this._whatever;
  }
  set
  {
    this._whatever = value;
  }
}

public void DoSomething()
{
  String s = this.Whatever;
  this.DoSomething();
}

(don't expect the code to do something sensible. I just wanted to show a few different uses for "this.")

I wonder why to do this? To add more clarity to the source?
Or is it just a waste of space?

like image 909
Sam Avatar asked Mar 17 '10 09:03

Sam


People also ask

How do you access internal classes?

Internal classes can't be visible outside of their assembly, so no explicit way to access it directly -AFAIK of course. The only way is to use runtime late-binding via reflection, then you can invoke methods and properties from the internal class indirectly.

What is internal access modifier?

The internal keyword is an access modifier for types and type members. This page covers internal access. The internal keyword is also part of the protected internal access modifier. Internal types or members are accessible only within files in the same assembly, as in this example: C# Copy.

How do you access class members C#?

To access the class members, you use the dot (.) operator. The dot operator links the name of an object with the name of a member.

What is access specifier C#?

C# Access modifiers or specifiers are the keywords that are used to specify accessibility or scope of variables and functions in the C# application. C# provides five types of access specifiers. Public. Protected. Internal.


1 Answers

It all reduces to personal preference and good practices.

In most situations it just doesn't matter but it might matter when you happen to have a parameter with the same name as a private field (which indicates a bad naming convention anyway).

From my personal point of view, any variable reference to a parameter or a field or almost whatever should be clear enough without the "this" qualifier... only when it is not and you can't change it to make it so, I use this.

like image 140
Jorge Córdoba Avatar answered Sep 19 '22 19:09

Jorge Córdoba