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?
Related
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.
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;
}
}
.Net 3.5 sp1 available type question ...
Is it possible to "get a handle" or reference to the actual instance of an assembly that called a method? I can get the executing and calling assembly via reflection, but what I'm after is not so much the assembly, but the INSTANCE of that assembly that called method.
Simple example (maybe):
interface IBob
{
int Id { get; }
void Foo();
}
public class Bob : IBob
{
private int _id = 123;
public int Id
{
get { return _id; }
}
public void Foo()
{
new OtherAssemblyClass().Bar();
}
}
public class OtherAssemblyClass
{
public void Bar()
{
//
// what I want to do here is get a reference
// to the calling INSTANCE of IBob and determine
// Bob's Id ... so something like:
//
// int Id = (System.XXX.GetCallingAssemblyInstance() as IBob).Id;
//
//
}
}
The real situation is a bit more complex than this, and precludes the obvious passing of IBob instance as a parameter in OtherAssemblyClass.Bar(), although that may be end result.
Entirely possible I'm just being stupid too, and not seeing obvious. 2 x 4 corrections to skull also welcome.
Unfortunately you can't get the instance unless it's passed in. You can find out what's calling your method by using the StackTrace.
PostSharp is the only way I would know of to make that work. Take a look at the InstanceBoundLaosEventArgs class. Warning: this is a pretty big deal, and a serious addition to the weight and complexity of your architecture, especially at build time.
I can get you halfway there if you are willing to use extension methods. Here's an example:
public static void Bar(this IBob CallingIBob)
{
int Id = CallingIBob.Id;
}
...and calling Bar():
public class Bob : IBob
{
#region IBob Members
public void Foo()
{
this.Bar();
}
public int Id
{
get { throw new NotImplementedException(); }
}
#endregion
}
Yes, it's not the exact case you were looking for, but functionally similar. Bar can be called from any bob and it will have a reference to the calling bob without explicitly passing in the instance.
I understand that you may want to call Bar in another assembly of your choice. Maybe Bar is defined in a base class and you are calling specific implementations of it in subclasses. That's ok, use the extension method to take in information about the specific Bar you are trying to access and route accordingly.
Please update your post with a more concrete problem definition if you would like a more specific solution.
All I need is a way to make a property of one class only 'settable' from one other class (a sort of manager class).
Is this even possible in c#?
My colleague 'reliably' informs me that I have a design flaw, but I feel I should at least ask the community before I concede defeat!
No, it's not really possible to do this in any clean way in C#. You probably have a design flaw ;-)
You can use the internal modifier, which lets all types in the same assembly access the data (or nominated assemblies if using [InternalsVisibleTo] - but no: there is no friend equivalent in C#.
For example:
public string Foo {get; internal set;}
You have a design flaw. Also, don't be paranoid about data hiding. Here's 3.5's way to do it:
class Program
{
static void Main(string[] args)
{
Managed m = new Managed();
Console.WriteLine(m.PrivateSetter);
m.Mgr.SetProperty("lol");
Console.WriteLine(m.PrivateSetter);
Console.Read();
}
}
public class Managed
{
private Manager _mgr;
public Manager Mgr
{
get { return _mgr ?? (_mgr = new Manager(s => PrivateSetter = s)); }
}
public string PrivateSetter { get; private set; }
public Managed()
{
PrivateSetter = "Unset";
}
}
public class Manager
{
private Action<string> _setPrivateProperty;
public Manager(Action<string> setter)
{
_setPrivateProperty = setter;
}
public void SetProperty(string value)
{
_setPrivateProperty(value);
}
}
Here's how we'd do it in pre-lambda days:
public class Managed
{
private Manager _mgr;
public Manager Mgr
{
get { return _mgr ?? (_mgr = new Manager(this)); }
}
public string PrivateSetter { get; private set; }
public Managed()
{
PrivateSetter = "Unset";
}
public class Manager
{
public void SetProperty(string value)
{
m.PrivateSetter = value;
}
private Managed m;
public Manager(Managed man)
{
m = man;
}
}
}
The best way to do it would be:
/// <summary>
/// Gets or sets foo
/// <b>Setter should only be invoked by SomeClass</b>
/// </summary>
public Object Foo
{
get { return foo; }
set { foo = value; }
}
When you have some complex access or inheritance restriction, and enforcing it demands too much complexity in the code, sometimes the best way to do it is just properly commenting it.
Note however that you cannot rely on this if this restriction has some security implications, as you are depending on the goodwill of the developer that will use this code.
You cannot do that on that way, but you can access a property's setter method from a derived class, so you can use inheritance for the purpose. All you have to do is to place protected access modifier. If you try to do so, your colleague is right :). You can try doing it like this:
public string Name
{
get{ return _name; }
protected set { _name = value; }
}
keep in mind that the set method of the property is only accessible from the derived class.
Or you could have these two classes in an assembly alone and have the setter as internal. I would vote up for the design flaw though, unless the previous answer by milot (inheriting and protected) makes sense.
You could do:
public void setMyProperty(int value, Object caller)
{
if(caller is MyManagerClass)
{
MyProperty = value;
}
}
This would mean that you could use a 'this' pointer from the calling class. I would question the logic of what you're attempting to achieve, but without knowing the scenario I can't advise any futher. What I will say is this: if it is possible to refactor your code to make it clearer, then it is often worthwhile doing so.
But this is pretty messy and certinly NOT fool-proof ... you have been warned!
Alternativly...
You could pass a delegate from the Class with the Property (Class A) to the Manager Class (Class B). The delegate can refer to a private function within A to allow B to call that delegate as any normal function. This precludes that A knows about B and potentially that A is created before B. Again... messy and not fool-proof!
You can achieve to this by making a Public property in your "settable class" that will inherit from the real class that will have a protected property... this way only the inherit class can SET and not class that doesn't inherit. But the drawback is that you will require to have an inherit class...
Reflection, though I would agree that having to do this just to get around an access modifier is probably an indication of a bad design.
public class Widget
{
private int count;
public int Count
{
get { return this.count; }
private set { this.count = value; }
}
}
public static class WidgetManager
{
public static void CatastrophicErrorResetWidgetCount( Widget widget )
{
Type type = widget.GetType();
PropertyInfo info = type.GetProperty("Count",BindingFlags.Instance|BindingFlags.NonPublic);
info.SetValue(widget,0,null);
}
}
The reason this is a design flaw is because it seems muddled between the scope of the two objects.
The properties of a class should be accessible in the context of that class, at least internally.
It sounds like the settable property on your item class is really a property of the manager class.
You could do something similar to what you want by closely coupling the two classes:
public class MyItem {
internal MyItemManager manager { get;set; }
public string Property1 {
get { return manager.GetPropertyForItem( this ); }
}
}
Unfortunately this isn't great design either.
What your looking for is what C++ calls a Friend class but neither c# or vb has this functionality. There is a lot of debate as to the merit of such functionality since it almost encourages very strong coupling between classes. The only way you could implement this in c# would be with reflection.
If your goal is to have a class Foo let some property (e.g. Bar, of type Biz) to be changed by some other object, without exposing it publicly, a simple way to do that is to have an instance of Foo which is supposed to be changeable by some other object to pass that other object an Action<Biz> which points to a private method that changes Bar to the passed-in value. The other object may use that delegate to change the Bar value of the object that supplied it.
If one wishes to have give all instances of some type Woozle the ability to set the Bar value of any instance of Foo, rather than exposing such abilities on a per-instance basis, one may require that Woozle have a public static method Woozle.InstallFooBarSetter which takes a parameter of type Action<Foo, Biz> and one of type Object. Foo should then have a static method WoozleRequestBarSetter which takes an Object, and passes it to Woozle.InstallFooBarSetter along with an Action<Foo,Biz>. The class initializer for Woozle should generate a new Object, and pass it to Foo.RequestBarSetter; that will pass the object to Woozle.InstallFooBarSetter along with a delegate. Woozle can then confirm that the passed-in object is the one that it generated, and--if so--install the appropriate delegate. Doing things this way will ensure that nobody but Woozle can get the delegate (since the delegate is only passed to Woozle.InstallFooBarSetter), and Woozle can be sure its delegate comes from Foo (since nobody else would have access to the object that Woozle created, and Woozle.InstallFooBarSetter won't do anything without it).
if it is a design flaw depends on what you want to do. You could use the StackTrace class from System.Diagnostics to get the Type of the class setting your property and then compare to the type you want to allow setting yor property..but maybe there are better ways for performing something like this (e.g. boxing)
Does anybody have useful example of this assignment inside a C# method? I have been asked for it once during job interview, and I am still interested in answer myself.
The other answers are incorrect when they say you cannot assign to 'this'. True, you can't for a class type, but you can for a struct type:
public struct MyValueType
{
public int Id;
public void Swap(ref MyValueType other)
{
MyValueType temp = this;
this = other;
other = temp;
}
}
At any point a struct can alter itself by assigning to 'this' like so.
using the this keyword ensures that only variables and methods scoped in the current type are accessed. This can be used when you have a naming conflict between a field/property and a local variable or method parameter.
Typically used in constructors:
private readonly IProvider provider;
public MyClass(IProvider provider)
{
this.provider = provider;
}
In this example we assign the parameter provider to the private field provider.
only correct place for this from syntax point of view, is Extension methods in C# 3.0 when you specify first parameter of method as foo(ftype this, ...). and then can use this extension for any instance of ftype. But is's just syntax and not real this ovveride operation.
if you're asked to assign something to this, there's quite a few examples. One that comes to mind is telling a control who his daddy is:
class frmMain
{
void InitializeComponents()
{
btnOK = new Button();
btnOK.Parent = this;
}
}
I know this question has long been answered and discussion has stopped, but here's a case I didn't see mentioned anywhere on the interwebs and thought it may be useful to share here.
I've used this to maintain immutability of members while still supporting serialization. Consider a struct defined like this:
public struct SampleStruct : IXmlSerializable
{
private readonly int _data;
public int Data { get { return _data; } }
public SampleStruct(int data)
{
_data = data;
}
#region IXmlSerializableMembers
public XmlSchema GetSchema() { return null; }
public void ReadXml(XmlReader reader)
{
this = new SampleStruct(int.Parse(reader.ReadString()));
}
public void WriteXml(XmlWriter writer
{
writer.WriteString(data.ToString());
}
#endregion
}
Since we're allowed to overwrite this, we can maintain the immutability of _data held within a single instance. This has the added benefit of when deserializing new values you're guaranteed a fresh instance, which is sometimes a nice guarantee!
}
You cannot overwrite "this". It points to the current object instance.