Why do some use `this.`? [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the purpose of 'this' keyword in C#.
Hello,
I have a question about something. I have had a look around, but can't seem to figure it out.
Why do some programmers use this in-front of something? Like:
this.button1 = String.Empty;
In MSDN, I don't ever recall seeing this. being used unless this. was referring to the Form itself, like this:
this.WindowState = FormWindowState.Minimized;
Is this how we're really supposed to reference things? Or, are there added benefits to doing it this way? So far, I have not experienced any noticeable benefits, not have I noticed any changes.
Thank you :-)

the keyword this is often used as a way to be explicit in where a variable is coming from. For example, a large function might have many variables, and using this may be used to tell what are true properties for a class being set, and what are function variables.
Also, consider the example below, where it's necessary to use the keyword to distinguish between a class variable and function parameter.
object one;
object two;
public MyClass(object one, object two)
{
this.one = one;
this.two = two;
}

Actually, you use this to reference the container object. Using this is usefull sometimes in solving some conflection cases as the following:
public class Person
{
private String name;
public Person(String name)
{
this.name = name;
}
}
However you can avoid using this by changing the name of the private field/variable:
public class Person
{
private String _name;
public Person(String name)
{
_name = name;
}
}

This means this object: if you're in a form that's a form, if you are in a simple class, that's your class. We're not supposed to use it (it's implicit), but sometimes you need it to make code very clear or it is necessary when:
class MyClass
{
private int tot = 0;
public MyClass(int tot)
{
this.tot = tot;
}
}

Do take a look at http://msdn.microsoft.com/en-us/library/dk1507sz(v=vs.71).aspx. Mostly we use it to ensure that we are referring to members of a class that might be hidden. The MSDN example is:
public Employee(string name, string alias)
{
this.name = name;
this.alias = alias;
}

Using this keyword in your code will differentiate which ones area the properties and methods of the class you are currently in scope. Also this means that we are using the instance methods and properties, not the static methods and properties.
This also means we have to instantiate it first.
Therefore, it will improve readability and the meanings of your code, especially in a large team of software developers where the code will be shared to others.

Something like this.button1 is necessary when there's another button1 in a more local scope than your object.

The this. notation is systematically used by the windows forms generator, this is maybe where you saw it.
this. is used for disambiguation when a member variable name is the same as a method parameter, for example.
Other than that, it's a matter of taste, but I believe most programmers do not use it because it's long to type (but a bit more readable, I'd say).

Remember that using "this." is sometimes mandatory. As an example, when assigning field values with the same name as constructor arguments, e.g.
public class MyClass{
private string name;
public MyClass(string name) {
this.name = name; // <== This is mandatory
}
}

for compiler it is the same. Form has controls as fields, and adding the this keyword simply remids the reader that we are using Form fields

It's unnecessary (the code will work fine without it), however it does make it clearer as to where the method or field belongs. If you use StyleCop on its most picky settings, Microsoft recommend this style.
Edit: Actually, most of the time it is unnecessary, but as several other answers have mentioned, it is sometimes necessary for conflict resolution.

SomeNameSpace.SomeClass.SomeMethod()
SomeNameSpace.SomeClass.OtherMethod()
when you're within SomeMethod(), say you want to call OtherMethod(). Using this prevents you from having to write SomeNameSpace.SomeClass.OtherMethod() every time that you want to use it.
Since you're within SomeClass already, this will reference SomeClass when you're working inside of SomeMethod(). So all you have to do to reference OtherMethod() is go: this.OtherMethod()
It's a nice shortcut that will also make your programs easier to maintain in the future, should you need to change SomeNameSpace or SomeClass to other names.. this will still work how you intended it to.
namespace Foo {
public class Bar {
public void Method() {
// Do Other Stuff
}
public void OtherMethod() {
// Do Some Stuff
this.Method(); // Do Other Stuff
// Instead of Foo.Bar.Method()
}
}
}

It is not mandatory but I believe the main reason for following this practice is to improve readability. As an example it makes it very easy for the reader to distinguish between local variables and method parameters.
public class User
{
string firstname;
string lastname;
public User(string firstname, string lastname)
{
this.firstname = firstname;
this.lastname = lastname;
}
}

Related

Why are Immutable classes not Sealed in C#

I am asking the question regarding Immutable object pattern and implementing it. I am not talking about the existing classes in .Net library like String.
I understand that immutable objects are objects which once loaded cannot be modified by any external or internal component. What if I derive the immutable class as it is not a sealed class. Then assign the object to the base class, and call a method in the base class. I have effectively changed the state of the base immutable class as its state is that of the derived class object.
public class Person
{
private readonly string name;
public Person(string myName)
{
this.name = myName;
}
public string Name
{
get { return this.name; }
}
public void DisplayName()
{
Console.WriteLine(string.Format("Person's name is {0}", this.name));
}
}
public class AnotherPerson : Person
{
private string name1;
public AnotherPerson (string myName) : base(myName)
{
this.name1 = myName;
}
}
class Program
{
static void Main(string[] args)
{
Person me = new Prasanth("MyName");
me.DisplayName();
me = new AnotherPerson("AnotherName"); ;
me.DisplayName();
Console.ReadLine();
}
}
Output :
Person's name is MyName
Person's name is AnotherName
Let's forget about the flaws of your example (the comments already said it all) and answer your question: "why are Immutable classes not Sealed in C#."
The thing is, immutability isn't a feature of the C# language. Some languages support immutability as a feature (in which case your point would be valid), but C# doesn't. In the end, you're just building an immutable class out of existing, all-purpose features. And therefore, limitations can ensue.
Also, immutability is a precaution, not a protection. The point is to prevent anybody to change the data through "normal" means. If somebody really wants to change the data, they always can, for instance through reflection (or sub-classing, as you mentioned). But if a developer does that, then there's no way he's ignoring he's mutating data that is supposed to be read-only, and we can assume he has a good reason to do so. The point of immutability is to prevent the developer from unknowingly shooting himself in the foot, not to lock him down.
You can only assign readonly string name once. I'm currently not sure if this only possible in the constructor.
You assign it in the first run "MyName" and in the second run you assing "AnotherName" to a completly different object that you created with new AnotherPerson(...)
static void Main(string[] args)
{
Person me = new Prasanth("MyName");
me.DisplayName();
// vvvvvv here you lose the reference to the old object
me = new AnotherPerson("AnotherName"); ;
me.DisplayName();
Console.ReadLine();
}

Is it better to use this. before code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I sometimes need to go online and find a tutorial for something. I am often finding that some people put code like this:
this.button1.Text = "Random Text";
Then I find code that is just like this:
button1.Text = "Random Text";
Is it better to use the this.whatever or does it not matter?
It depends. Here's an example class:
class A
{
private int count;
public A(int count)
{
this.count = count;
}
}
In this case, the "this." is mandatory because it disambiguates the reference on the left of the assignment. Without it, it is not clear to you reading the code whether "count" would refer to the parameter or the field. (It is clear to the compiler, which has rules to follow.) But in most cases, it is purely a matter of preference.
Write all your code to emphasize salient points to the reader. If you feel that it is important for the reader to clearly understand that an identifier refers to an instance member then use this. If you feel that its an unimportant and distracting implementation detail, don't. Use good judgment to make your code readable.
this is just to make it clear, in some cases we have to use this:
Differentiate between parameter and local member:
//local member
object item;
private void SomeMethod(object item){
this.item = item;//must use this
}
Pass the current class instance into another method:
public class SomeClass {
private void SomeMethod(SomeClass obj){
//....
}
private void AnotherMethod(){
SomeMethod(this);//pass the current instance into SomeMethod
//.....
}
}
Use in extension methods:
public static class SomeClassExtension {
public static void SomeClassMethod(this SomeClass obj){
//use obj as a reference to the object calling this method...
}
}
Call a constructor from another constructor (with different signature):
public Form1(string s) : this() {//Call the Form1() before executing other code in Form1(string s)
//......
}
Use for declaring indexers:
public class SomeClass {
//declare an index returning a string
public string this[int index] {
get {return ...}
set { ... }
}
}
Use auto-properties in struct:
public struct SomeStruct {
public object AutoProp1 {get;set;}
public object AutoProp2 {get;set;}
public SomeStruct() : this() //must use this
{
AutoProp1 = someObject;
AutoProp2 = someObject;
}
}
Cast the current instance to the based classes/types:
public class ClassB : ClassC {
//...
}
public class ClassA : ClassB {
public ClassA(){
((ClassC)this).MemberOfClassC ... ;//There might be some member in ClassC
//which is overridden in ClassA or ClassB, casting to ClassC can help we invoke the original member instead of the overridden one.
}
}
There might be some other uses of this, however I'll update later if I think out.
It does not matter, it is a matter of style. I tend to omit this, since it is just extra code to mentally parse.
The only case it matters is when there is a naming conflict between local and instance variables, in which case this can be used to disambiguate between a field and a local variable.
Here is an example of the type of situation where it does matter:
public class Foo
{
private string x;
public Foo(string x)
{
// x = x; Assigns local parameter x to x, not what we want
this.x = x; // Assigns instance variable x to local parameter x: this disambiguates between the two.
}
}
an example of using this can be to access class variable when you already have a similar variable in the scope. Otherwise it is mostly of choice.
Example
public class Test
{
public string firstName { get; set; }
public void temp(string firstName)
{
firstName = this.firstName;
}
}
In regards to fields the only case where this is explicitly needed is when there is a naming conflict:
public class Foo
{
private string bar;
public Foo(string bar)
{
this.bar = bar;
}
}
So some will prepend an underscore:
public class Foo
{
private string _bar;
public Foo(string bar)
{
_bar = bar;
}
}
Usually it will not matter. This reason why you might use this. is to explicit say that you want to reference a property/field that belong to the current class.
Again, there are not many occasions when you are likely to need this, but for example you might have a local variable with the same name as a class level property/field. Then you could use this..
For example:
class MyClass
{
string s = "1";
void MyFunction(string s)
{
//s = local value as passed in to function
//this.s = "1"
}
}
It doesn't usually matter. The this keyword "refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method."
Check out this article.
http://msdn.microsoft.com/en-us/library/dk1507sz.aspx
generally it doesn't matter, but if you pass in a variable called, say button1, to a class method that already has a member called button1, then you'll need to disambiguate which one you really meant.
This is probably why people now use this. to explicitly say which variable you meant, if you use this practice all the time, you'll not get it wrong in the few cases where its important.
Of course, you could ensure that all member variables are uniquely named, say with a prefix like m_, but that's fallen out of fashion nowadays, people prefer to write out this.
It really depends on the situation.
http://msdn.microsoft.com/en-us/library/dk1507sz(v=vs.80).aspx
To qualify members hidden by similar names
To pass an object as a parameter to other methods
To declare indexers
As others have already pointed out, it is useful in distinguishing field/property with method variables, One other place where this is required is to invoke Extension methods on current instance. For example this.ExtensionMethod(); would work, but not just ExtensionMethod();
Other than that, its a matter of personal choice, some call it redundant and some like to use it. It totally depends on you and your team.
Personally I like to use this with class members, specially for Forms method if working on code-behind of winform, like this.Close();
For more discussion when to use this see: When do you use the "this" keyword?

Creating a function for getting a variable value [duplicate]

This question already has answers here:
Difference between Property and Field in C# 3.0+
(10 answers)
Closed 9 years ago.
Should I prefer getting variable from other class directly(int number = something.number;) or should I use a function for getting that number(like in example below)? What is the difference?
class someclass
{
private int number;
public float GetSomething()
{
return number;
}
}
class otherclass
{
someclass something;
private void somefunction()
{
int number = something.GetSomething();
}
}
The difference between using a field reference or a getter method is that if you create a method that you expect "client code" to use, then you can always change the method code later and the client will not have to change his code. If you use a field, then the client will have to update their code from using the field to using a method, if you decide that you want, for example, validation in the method. So, in short, it is better practice to use getter methods for future-proofing. However, in a language like C#, you can also use properties, which act like methods but look like fields, so you can have the best of both worlds: nice syntax (fields), and future-proofing (methods).
for that type of data, you'd better use a property :
class someclass
{
private int number;
public int Number
{
get {return number;}
set {number = value;}
}
}
then you can use someclass.Number anywhere else
Direct accessing to a class variable outside of a class is not a good practice so it's strongly recommended to use methods (also include properties).
When there is no direct access to your class variables, other classes can use it and whenever you change the internal structure of your class you can do it with less effort. Consider you class:
class someclass
{
// it's a field
private int number;
// it's a property
public int Number
{
get{return this.number;}
}
//or you can use method
}
EDIT: If after a while you found that it was better to change the number's type to int?, you can do it because never outside the class anyone uses number so simply you can make changes to number and change your property this way
class someclass
{
private int? number;
public int Number
{
get{return this.number.Value;}
}
//or you can use method
}
Exposing fields is bad practice because it less extensive than expose method or property. For example you want to change this field's calculation logic depending on other fields values. That will be possible with both approaches but if you will use methods or properties it will be easier and cleaner to implement.

C# Java-like inline extension of classes?

I would look this up on Google/MSDN, but I have no idea what it's called so I'm asking here.
In Java, I seem to remember you can do this really cool thing like:
Class MyClass
{
int number;
MyClass() { }
void setNumber(int number)
{
this.number = number;
}
}
and then do something like:
MyClass myClass = new MyClass()
{
override void setNumber(int Number)
{
this.number = 2 * number;
}
};
...or something. Forgive any mistakes I made above - I haven't actually touched Java in about 6 years.
The point is, I remember you could pseudo-extend a class inline.
Right now, I need to extend a C# WinForms control, but I only need to use it once, and the modifications are very minor. All I need to do is to override the CreateParams property and OnPaint() handler.
My solution is already getting huge with classes all over the place, it seems like a shame to include yet another class which is basically identical to a standard .Net control, just with very slightly different behaviour.
Is it possible to do this inline-extension in C# like you could in Java? If so, how? (and what is it called so I can look it up on MSDN?)
This (explicit nominative anonymous types) is not possible in C#3/4.
The types must be created explicitly and then constructed. Tasks are sometimes "inverted" in C# with the use of Events and Delegates (class invokes Event which supplies implementation such as "NeedDataSource") -- arguably because of this, although it just makes sense in many cases.
If is possible to create explicit non-nominative types: var x = new { P = 1, }; but only in a local scope. Implicit methods include delegates/lambdas/anonymous functions and do not apply here.
Happy coding.
I understand that you said this cannot be done in C#, but its possible to rewrite this to C# but with not too much complicated method?
new EffectClause("Sleep Clause", SleepEffect.class)
{
public String getClauseDescription()
{
return "Bla bla bla";
}
public boolean isEnabledByDefault()
{
return true;
}
};
The feature you're looking for in C# is called Extension Methods. They are similar, but instead you make code such as:
public static void setNumber(int Number, MyClass target)
{
target.number = 2 * number;
}
You usually include this in your own extensions namespace, then bring it into scope when necessary by using MyExtensions; C# is able to figure out that you mean to call this method when you call whatever.setNumber(x);
I'm not 100% sure if this will let you override a method that already exists in a class however. Your other option is to inherit from the target class with a class specifically for the purpose of overriding the target method.

Using certain variables in different classes (C#)

I'm pretty new to C# and I was trying out a few things. I have a label (named 'newLabel') in the form1.cs. I have a class named 'methods.cs'. In this class I have the method
public static void updateLabel()
what I want to do is:
public static void updateLabel()
{
newLabel.Text = "New Value";
}
but this doesn't work, probably because the method is in methods.cs and the newLabel is in form1.cs.
I had the same problem with declared variables. In the methods.cs I had the variable
int value;
but I couldn't use this variable in form1.cs. I fixed this by doing
public static int value { get; set; }
I have no idea what that did but it works, but I don't know how I can apply this trick with the label.
Could someone help me with this?
Thanks!
You should read up about OOP and encapsulation. Basically you want the form
to access private fields in another object (your class) - this is restricted by encapsulation, that's why you are running into problem - you can get around them by adding those fields and methods to the "public" interface that your class is declaring by making them public properties and methods, i.e in your example:
public int Value {get;set;}
Sometimes composition is used, i.e. in your example since your class is directly accessing the form you could have a form property on your class:
public Form ViewForm {get;set;}
It would be best if you learnt C# from tutorials, but the answer to this particular question lies with something called "scope"
Essentially, scope is the visibility of variables, classes, functions and objects. A variable marked "private" can only be seen within the thing that created it (if it's created inside a function it will always be private and any variables defined inside a function can only be used inside that function). If it's created inside a class only that class can use it.
Variables or functions denoted as public (this can only be done inside a class) can be seen from outside that class. To do that you would invoke myClass.myVariable to access the variable or myClass.myFunction() to access the function.
To denote the visibility of an object you use the keywords "public" or "private". Note: This only applies to variables and functions inside classes (it also applies to other things within classes, such as nested classes and structs, but that's outside the scope of this basic intro).
for example:
class myClass
{
private int myInt;
public void myfunction()
{
myInt = 1;
}
}
This will work, as myInt can be seen by anything inside myClass
class myOtherClass
{
private void myfunction()
{
myClass myObject = new myClass();
myObject.myInt = 2;
}
}
This will not, as myInt is private to myObject and only myObject can change it. myOtherClass does not have permission and it cannot see it.
class myOtherClassTwo
{
private void myfunction()
{
myClass myObject = new myClass();
myObject.myFunction();
}
}
This, thankfully, will work. myFunction was set as public in the myClass class, so it can be seen by anybody outside of the class.
Now the keyword static which you use has a whole different meaning. I advise you not to use it until you've learned about it as you're only adding additional complexity to your problems.
I hope this has cleared things up, though I must urge you to follow some real tutorials as these basics must be thoroughly detailed or you'll be caught out later on.
Since your updateLabel method accesses the label inside the form, correct object-oriented design would dictate that this method should be in the form, too. Then you have no problem accessing newLabel.
Technically speaking: newLabel doesn’t mean anything outside a form object. You could have several copies of your form, which would mean several copies of your newLabel; which of them should it refer to? Of course the computer won’t take a guess there; it’ll expect that you tell it which form you want to use.
The reason you couldn’t access the value variable is because it was private. If you had changed it simply to:
public static int value;
then it would have worked.
From the Form1, call the updateLabel method in the mothods class:
methods updateMethod = new methods();
newLabel.Text = updateMethod.updateLabel();
With this method in the methods class:
public static string updateLabel(){
return "New Value";
}

Categories