Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have seen samples of closure from - What is a 'Closure'?
Can anyone provide simple example of when to use closure?
Specifically, scenarios in which closure makes sense?
Lets assume that the language doesn't have closure support, how would one still achieve similar thing?
Not to offend anyone, please post code samples in a language like c#, python, javascript, ruby etc. I am sorry, I do not understand functional languages yet.
Closures are simply great tools. When to use them? Any time you like... As has already been said, the alternative is to write a class; for example, pre C# 2.0, creating a parameterised thread was a real struggle. With C# 2.0 you don't even need the `ParameterizedThreadStart' you just do:
string name = // blah
int value = // blah
new Thread((ThreadStart)delegate { DoWork(name, value);}); // or inline if short
Compare that to creating a class with a name and value
Or likewise with searching for a list (using a lambda this time):
Person person = list.Find(x=>x.Age > minAge && x.Region == region);
Again - the alternative would be to write a class with two properties and a method:
internal sealed class PersonFinder
{
public PersonFinder(int minAge, string region)
{
this.minAge = minAge;
this.region = region;
}
private readonly int minAge;
private readonly string region;
public bool IsMatch(Person person)
{
return person.Age > minAge && person.Region == region;
}
}
...
Person person = list.Find(new PersonFinder(minAge,region).IsMatch);
This is fairly comparable to how the compiler does it under the bonnet (actually, it uses public read/write fields, not private readonly).
The biggest caveat with C# captures is to watch the scope; for example:
for(int i = 0 ; i < 10 ; i++) {
ThreadPool.QueueUserWorkItem(delegate
{
Console.WriteLine(i);
});
}
This might not print what you expect, since the variable i is used for each. You could see any combination of repeats - even 10 10's. You need to carefully scope captured variables in C#:
for(int i = 0 ; i < 10 ; i++) {
int j = i;
ThreadPool.QueueUserWorkItem(delegate
{
Console.WriteLine(j);
});
}
Here each j gets captured separately (i.e. a different compiler-generated class instance).
Jon Skeet has a good blog entry covering C# and java closures here; or for more detail, see his book C# in Depth, which has an entire chapter on them.
I agree with a previous answer of "all the time". When you program in a functional language or any language where lambdas and closures are common, you use them without even noticing. It's like asking "what is the scenario for a function?" or "what is the scenario for a loop?" This isn't to make the original question sound dumb, rather it's to point out that there are constructs in languages that you don't define in terms of specific scenarios. You just use them all the time, for everything, it's second nature.
This is somehow reminiscent of:
The venerable master Qc Na was walking
with his student, Anton. Hoping to
prompt the master into a discussion,
Anton said "Master, I have heard that
objects are a very good thing - is
this true?" Qc Na looked pityingly at
his student and replied, "Foolish
pupil - objects are merely a poor
man's closures."
Chastised, Anton took his leave from
his master and returned to his cell,
intent on studying closures. He
carefully read the entire "Lambda: The
Ultimate..." series of papers and its
cousins, and implemented a small
Scheme interpreter with a
closure-based object system. He
learned much, and looked forward to
informing his master of his progress.
On his next walk with Qc Na, Anton
attempted to impress his master by
saying "Master, I have diligently
studied the matter, and now understand
that objects are truly a poor man's
closures." Qc Na responded by hitting
Anton with his stick, saying "When
will you learn? Closures are a poor
man's object." At that moment, Anton
became enlightened.
(http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html)
The most simple example of using closures is in something called currying. Basically, let's assume we have a function f() which, when called with two arguments a and b, adds them together. So, in Python, we have:
def f(a, b):
return a + b
But let's say, for the sake of argument, that we only want to call f() with one argument at a time. So, instead of f(2, 3), we want f(2)(3). This can be done like so:
def f(a):
def g(b): # Function-within-a-function
return a + b # The value of a is present in the scope of g()
return g # f() returns a one-argument function g()
Now, when we call f(2), we get a new function, g(); this new function carries with it variables from the scope of f(), and so it is said to close over those variables, hence the term closure. When we call g(3), the variable a (which is bound by the definition of f) is accessed by g(), returning 2 + 3 => 5
This is useful in several scenarios. For example, if I had a function which accepted a large number of arguments, but only a few of them were useful to me, I could write a generic function like so:
def many_arguments(a, b, c, d, e, f, g, h, i):
return # SOMETHING
def curry(function, **curry_args):
# call is a closure which closes over the environment of curry.
def call(*call_args):
# Call the function with both the curry args and the call args, returning
# the result.
return function(*call_args, **curry_args)
# Return the closure.
return call
useful_function = curry(many_arguments, a=1, b=2, c=3, d=4, e=5, f=6)
useful_function is now a function which only needs 3 arguments, instead of 9. I avoid having to repeat myself, and also have created a generic solution; if I write another many-argument function, I can use the curry tool again.
Typically, if one doesn't have closures, one must define a class to carry with it the equivalent of the closure's environment, and pass it around.
For example, in a language like Lisp, one can define a function that returns a function (with a closed-over environment) to add some predefined amount to its argument thusly:
(defun make-adder (how-much)
(lambda (x)
(+ x how-much)))
and use it like this:
cl-user(2): (make-adder 5)
#<Interpreted Closure (:internal make-adder) # #x10009ef272>
cl-user(3): (funcall * 3) ; calls the function you just made with the argument '3'.
8
In a language without closures, you would do something like this:
public class Adder {
private int howMuch;
public Adder(int h) {
howMuch = h;
}
public int doAdd(int x) {
return x + howMuch;
}
}
and then use it like this:
Adder addFive = new Adder(5);
int addedFive = addFive.doAdd(3);
// addedFive is now 8.
The closure implicitly carries its environment with it; you seamlessly refer to that environment from inside the executing part (the lambda). Without closures you must make that environment explicit.
That should explain to you when you would use closures: all the time. Most instances where a class is instantiated to carry with it some state from another part of the computation and apply it elsewhere are elegantly replaced by closures in languages which support them.
One can implement an object system with closures.
Here is an example from Python's standard library, inspect.py. It currently reads
def strseq(object, convert, join=joinseq):
"""Recursively walk a sequence, stringifying each element."""
if type(object) in (list, tuple):
return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
else:
return convert(object)
This has, as parameters, a convert function and a join function, and recursively walks over lists and tuples. The recursion is implemented using map(), where the first parameter is a function. The code predates the support for closures in Python, so needs two additional default arguments, to pass convert and join into the recursive call. With closures, this reads
def strseq(object, convert, join=joinseq):
"""Recursively walk a sequence, stringifying each element."""
if type(object) in (list, tuple):
return join(map(lambda o: strseq(o, convert, join), object))
else:
return convert(object)
In OO languages, you typically don't use closures too often, as you can use objects to pass state - and bound methods, when your language has them. When Python didn't have closures, people said that Python emulates closures with objects, whereas Lisp emulates objects with closures. As an example from IDLE (ClassBrowser.py):
class ClassBrowser: # shortened
def close(self, event=None):
self.top.destroy()
self.node.destroy()
def init(self, flist):
top.bind("<Escape>", self.close)
Here, self.close is a parameter-less callback invoked when Escape is pressed. However, the close implementation does need parameters - namely self, and then self.top, self.node. If Python didn't have bound methods, you could write
class ClassBrowser:
def close(self, event=None):
self.top.destroy()
self.node.destroy()
def init(self, flist):
top.bind("<Escape>", lambda:self.close())
Here, the lambda would get "self" not from a parameter, but from the context.
In Lua and Python it's a very natural thing to do when "just coding", because the moment you reference something that's not a parameter, you're making a closure. (so most of these will be quite dull as examples.)
As for a concrete case, imagine an undo/redo system, where the steps are pairs of (undo(), redo()) closures. The more cumbersome ways of doing that might be to either: (a) Make unredoable classes have a special method with universally dorky arguments, or (b) subclass UnReDoOperation umpteen times.
Another concrete example is infinite lists: Instead of working with genericized containers, you frob a function that retrieves the next element. (this is part of the power of iterators.) In this case you can either keep just little bit of state (the next integer, for the list-of-all-nonnegative-integers or similar) or a reference to a position in an actual container. Either way, it's a function that references something that is outside itself. (in the infinite-list case, the state variables must be closure variables, because otherwise they'd be clean for every call)
I'm told there are more uses in haskell, but I've only had the pleasure of using closures in javascript, and in javascript I don't much see the point. My first instinct was to scream "oh no, not again" at what a mess the implementation must be to make closures work.
After I read about how closures were implemented (in javascript anyway), it doesn't seem quite so bad to me now and the implementation seems somewhat elegant, to me at least.
But from that I realized "closure" isn't really the best word to describe the concept. I think it should better be named "flying scope."
As one of the previous answers notes, you often find yourself using them without hardly noticing that you are.
A case in point is that they are very commonly used in setting up UI event handling to gain code reuse while still allowing access to the UI context. Here's an example of how defining an anonymous handler function for a click event creates a closure that includes the button and color parameters of the setColor() function:
function setColor(button, color) {
button.addEventListener("click", function()
{
button.style.backgroundColor = color;
}, false);
}
window.onload = function() {
setColor(document.getElementById("StartButton"), "green");
setColor(document.getElementById("StopButton"), "red");
}
Note: for accuracy it's worth noting that the closure is not actually created until the setColor() function exits.
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:
In a constructor:
public Light(Vector v)
{
this.dir = new Vector(v);
}
Elsewhere
public void SomeMethod()
{
Vector vec = new Vector();
double d = (vec * vec) - (this.radius * this.radius);
}
I don't mean this to sound snarky, but it doesn't matter.
Seriously.
Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help you ship on time. It's not going to reduce bugs, it's not going to have any appreciable effect on code quality or maintainability. It's not going to get you a raise, or allow you to spend less time at the office.
It's really just a style issue. If you like "this", then use it. If you don't, then don't. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer's notions of what the "most aesthetically pleasing code" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn't like, or would have done differently. At some point some guy is going to read your code and grumble about something.
I wouldn't fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn't going to be scrutinizing how you initialize fields. He's just going to use your code, marvel at it's greatness, and then move on to something else.
There are several usages of this keyword in C#.
To qualify members hidden by similar name
To have an object pass itself as a parameter to other methods
To have an object return itself from a method
To declare indexers
To declare extension methods
To pass parameters between constructors
To internally reassign value type (struct) value.
To invoke an extension method on the current instance
To cast itself to another type
To chain constructors defined in the same class
You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties.
I only use it when absolutely necessary, ie, when another variable is shadowing another. Such as here:
class Vector3
{
float x;
float y;
float z;
public Vector3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
Or as Ryan Fox points out, when you need to pass this as a parameter. (Local variables have precedence over member variables)
Personally, I try to always use this when referring to member variables. It helps clarify the code and make it more readable. Even if there is no ambiguity, someone reading through my code for the first time doesn't know that, but if they see this used consistently, they will know if they are looking at a member variable or not.
I use it every time I refer to an instance variable, even if I don't need to. I think it makes the code more clear.
I can't believe all of the people that say using it always is a "best practice" and such.
Use "this" when there is ambiguity, as in Corey's example or when you need to pass the object as a parameter, as in Ryan's example. There is no reason to use it otherwise because being able to resolve a variable based on the scope chain should be clear enough that qualifying variables with it should be unnecessary.
EDIT: The C# documentation on "this" indicates one more use, besides the two I mentioned, for the "this" keyword - for declaring indexers
EDIT: #Juan: Huh, I don't see any inconsistency in my statements - there are 3 instances when I would use the "this" keyword (as documented in the C# documentation), and those are times when you actually need it. Sticking "this" in front of variables in a constructor when there is no shadowing going on is simply a waste of keystrokes and a waste of my time when reading it, it provides no benefit.
I use it whenever StyleCop tells me to. StyleCop must be obeyed. Oh yes.
Any time you need a reference to the current object.
One particularly handy scenario is when your object is calling a function and wants to pass itself into it.
Example:
void onChange()
{
screen.draw(this);
}
I tend to use it everywhere as well, just to make sure that it is clear that it is instance members that we are dealing with.
I use it anywhere there might be ambiguity (obviously). Not just compiler ambiguity (it would be required in that case), but also ambiguity for someone looking at the code.
Another somewhat rare use for the this keyword is when you need to invoke an explicit interface implementation from within the implementing class. Here's a contrived example:
class Example : ICloneable
{
private void CallClone()
{
object clone = ((ICloneable)this).Clone();
}
object ICloneable.Clone()
{
throw new NotImplementedException();
}
}
Here's when I use it:
Accessing Private Methods from within the class (to differentiate)
Passing the current object to another method (or as a sender object, in case of an event)
When creating extension methods :D
I don't use this for Private fields because I prefix private field variable names with an underscore (_).
[C++]
I agree with the "use it when you have to" brigade. Decorating code unnecessarily with this isn't a great idea because the compiler won't warn you when you forget to do it. This introduces potential confusion for people expecting this to always be there, i.e. they'll have to think about it.
So, when would you use it? I've just had a look around some random code and found these examples (I'm not passing judgement on whether these are good things to do or otherwise):
Passing "yourself" to a function.
Assigning "yourself" to a pointer or something like that.
Casting, i.e. up/down casting (safe or otherwise), casting away constness, etc.
Compiler enforced disambiguation.
You should always use it, I use it to diferantiate private fields and parameters (because our naming conventions state that we don't use prefixes for member and parameter names (and they are based on information found on the internet, so I consider that a best practice))
I use it when, in a function that accepts a reference to an object of the same type, I want to make it perfectly clear which object I'm referring to, where.
For example
class AABB
{
// ... members
bool intersects( AABB other )
{
return other.left() < this->right() &&
this->left() < other.right() &&
// +y increases going down
other.top() < this->bottom() &&
this->top() < other.bottom() ;
}
} ;
(vs)
class AABB
{
bool intersects( AABB other )
{
return other.left() < right() &&
left() < other.right() &&
// +y increases going down
other.top() < bottom() &&
top() < other.bottom() ;
}
} ;
At a glance which AABB does right() refer to? The this adds a bit of a clarifier.
In Jakub Šturc's answer his #5 about passing data between contructors probably could use a little explanation. This is in overloading constructors and is the one case where use of this is mandatory. In the following example we can call the parameterized constructor from the parameterless constructor with a default parameter.
class MyClass {
private int _x
public MyClass() : this(5) {}
public MyClass(int v) { _x = v;}
}
I've found this to be a particularly useful feature on occasion.
I got in the habit of using it liberally in Visual C++ since doing so would trigger IntelliSense ones I hit the '>' key, and I'm lazy. (and prone to typos)
But I've continued to use it, since I find it handy to see that I'm calling a member function rather than a global function.
I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...
I pretty much only use this when referencing a type property from inside the same type. As another user mentioned, I also underscore local fields so they are noticeable without needing this.
I use it only when required, except for symmetric operations which due to single argument polymorphism have to be put into methods of one side:
boolean sameValue (SomeNum other) {
return this.importantValue == other.importantValue;
}
[C++]
this is used in the assignment operator where most of the time you have to check and prevent strange (unintentional, dangerous, or just a waste of time for the program) things like:
A a;
a = a;
Your assignment operator will be written:
A& A::operator=(const A& a) {
if (this == &a) return *this;
// we know both sides of the = operator are different, do something...
return *this;
}
this on a C++ compiler
The C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:
using the mother class' method if you did not overloaded it in the child class.
promoting a value of a type into another type
But sometimes, You just don't want the compiler to guess. You want the compiler to pick-up the right symbol and not another.
For me, those times are when, within a method, I want to access to a member method or member variable. I just don't want some random symbol picked up just because I wrote printf instead of print. this->printf would not have compiled.
The point is that, with C legacy libraries (§), legacy code written years ago (§§), or whatever could happen in a language where copy/pasting is an obsolete but still active feature, sometimes, telling the compiler to not play wits is a great idea.
These are the reasons I use this.
(§) it's still a kind of mystery to me, but I now wonder if the fact you include the <windows.h> header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace
(§§) realizing that "you need to include a header, but that including this header will break your code because it uses some dumb macro with a generic name" is one of those russian roulette moments of a coder's life
'this.' helps find members on 'this' class with a lot of members (usually due to a deep inheritance chain).
Hitting CTRL+Space doesn't help with this, because it also includes types; where-as 'this.' includes members ONLY.
I usually delete it once I have what I was after: but this is just my style breaking through.
In terms of style, if you are a lone-ranger -- you decide; if you work for a company stick to the company policy (look at the stuff in source control and see what other people are doing). In terms of using it to qualify members, neither is right or wrong. The only wrong thing is inconsistency -- that is the golden rule of style. Leave the nit-picking others. Spend your time pondering real coding problems -- and obviously coding -- instead.
I use it every time I can. I believe it makes the code more readable, and more readable code equals less bugs and more maintainability.
When you are many developers working on the same code base, you need some code guidelines/rules. Where I work we've desided to use 'this' on fields, properties and events.
To me it makes good sense to do it like this, it makes the code easier to read when you differentiate between class-variables and method-variables.
It depends on the coding standard I'm working under. If we are using _ to denote an instance variable then "this" becomes redundant. If we are not using _ then I tend to use this to denote instance variable.
I use it to invoke Intellisense just like JohnMcG, but I'll go back and erase "this->" when I'm done. I follow the Microsoft convention of prefixing member variables with "m_", so leaving it as documentation would just be redundant.
1 - Common Java setter idiom:
public void setFoo(int foo) {
this.foo = foo;
}
2 - When calling a function with this object as a parameter
notifier.addListener(this);
There is one use that has not already been mentioned in C++, and that is not to refer to the own object or disambiguate a member from a received variable.
You can use this to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.
template <typename T>
struct base {
void f() {}
};
template <typename T>
struct derived : public base<T>
{
void test() {
//f(); // [1] error
base<T>::f(); // quite verbose if there is more than one argument, but valid
this->f(); // f is now an argument dependent symbol
}
}
Templates are compiled with a two pass mechanism. During the first pass, only non-argument dependent names are resolved and checked, while dependent names are checked only for coherence, without actually substituting the template arguments.
At that step, without actually substituting the type, the compiler has almost no information of what base<T> could be (note that specialization of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent call f that seems just natural to the programmer is a symbol that the compiler must find as a member of derived or in enclosing namespaces --which does not happen in the example-- and it will complain.
The solution is turning the non-dependent name f into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (base<T>::f --adding the base<T> makes the symbol dependent on T and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.
The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a this-> before the symbol. As the template class you are implementing does depend on an argument (it inherits from base<T>) this-> is argument dependent, and we get the same result: this->f is checked in the second round, after template parameter substitution.
You should not use "this" unless you absolutely must.
There IS a penalty associated with unnecessary verbosity. You should strive for code that is exactly as long as it needs to be, and no longer.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:
In a constructor:
public Light(Vector v)
{
this.dir = new Vector(v);
}
Elsewhere
public void SomeMethod()
{
Vector vec = new Vector();
double d = (vec * vec) - (this.radius * this.radius);
}
I don't mean this to sound snarky, but it doesn't matter.
Seriously.
Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help you ship on time. It's not going to reduce bugs, it's not going to have any appreciable effect on code quality or maintainability. It's not going to get you a raise, or allow you to spend less time at the office.
It's really just a style issue. If you like "this", then use it. If you don't, then don't. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer's notions of what the "most aesthetically pleasing code" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn't like, or would have done differently. At some point some guy is going to read your code and grumble about something.
I wouldn't fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn't going to be scrutinizing how you initialize fields. He's just going to use your code, marvel at it's greatness, and then move on to something else.
There are several usages of this keyword in C#.
To qualify members hidden by similar name
To have an object pass itself as a parameter to other methods
To have an object return itself from a method
To declare indexers
To declare extension methods
To pass parameters between constructors
To internally reassign value type (struct) value.
To invoke an extension method on the current instance
To cast itself to another type
To chain constructors defined in the same class
You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties.
I only use it when absolutely necessary, ie, when another variable is shadowing another. Such as here:
class Vector3
{
float x;
float y;
float z;
public Vector3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
Or as Ryan Fox points out, when you need to pass this as a parameter. (Local variables have precedence over member variables)
Personally, I try to always use this when referring to member variables. It helps clarify the code and make it more readable. Even if there is no ambiguity, someone reading through my code for the first time doesn't know that, but if they see this used consistently, they will know if they are looking at a member variable or not.
I use it every time I refer to an instance variable, even if I don't need to. I think it makes the code more clear.
I can't believe all of the people that say using it always is a "best practice" and such.
Use "this" when there is ambiguity, as in Corey's example or when you need to pass the object as a parameter, as in Ryan's example. There is no reason to use it otherwise because being able to resolve a variable based on the scope chain should be clear enough that qualifying variables with it should be unnecessary.
EDIT: The C# documentation on "this" indicates one more use, besides the two I mentioned, for the "this" keyword - for declaring indexers
EDIT: #Juan: Huh, I don't see any inconsistency in my statements - there are 3 instances when I would use the "this" keyword (as documented in the C# documentation), and those are times when you actually need it. Sticking "this" in front of variables in a constructor when there is no shadowing going on is simply a waste of keystrokes and a waste of my time when reading it, it provides no benefit.
I use it whenever StyleCop tells me to. StyleCop must be obeyed. Oh yes.
Any time you need a reference to the current object.
One particularly handy scenario is when your object is calling a function and wants to pass itself into it.
Example:
void onChange()
{
screen.draw(this);
}
I tend to use it everywhere as well, just to make sure that it is clear that it is instance members that we are dealing with.
I use it anywhere there might be ambiguity (obviously). Not just compiler ambiguity (it would be required in that case), but also ambiguity for someone looking at the code.
Another somewhat rare use for the this keyword is when you need to invoke an explicit interface implementation from within the implementing class. Here's a contrived example:
class Example : ICloneable
{
private void CallClone()
{
object clone = ((ICloneable)this).Clone();
}
object ICloneable.Clone()
{
throw new NotImplementedException();
}
}
Here's when I use it:
Accessing Private Methods from within the class (to differentiate)
Passing the current object to another method (or as a sender object, in case of an event)
When creating extension methods :D
I don't use this for Private fields because I prefix private field variable names with an underscore (_).
[C++]
I agree with the "use it when you have to" brigade. Decorating code unnecessarily with this isn't a great idea because the compiler won't warn you when you forget to do it. This introduces potential confusion for people expecting this to always be there, i.e. they'll have to think about it.
So, when would you use it? I've just had a look around some random code and found these examples (I'm not passing judgement on whether these are good things to do or otherwise):
Passing "yourself" to a function.
Assigning "yourself" to a pointer or something like that.
Casting, i.e. up/down casting (safe or otherwise), casting away constness, etc.
Compiler enforced disambiguation.
You should always use it, I use it to diferantiate private fields and parameters (because our naming conventions state that we don't use prefixes for member and parameter names (and they are based on information found on the internet, so I consider that a best practice))
I use it when, in a function that accepts a reference to an object of the same type, I want to make it perfectly clear which object I'm referring to, where.
For example
class AABB
{
// ... members
bool intersects( AABB other )
{
return other.left() < this->right() &&
this->left() < other.right() &&
// +y increases going down
other.top() < this->bottom() &&
this->top() < other.bottom() ;
}
} ;
(vs)
class AABB
{
bool intersects( AABB other )
{
return other.left() < right() &&
left() < other.right() &&
// +y increases going down
other.top() < bottom() &&
top() < other.bottom() ;
}
} ;
At a glance which AABB does right() refer to? The this adds a bit of a clarifier.
In Jakub Šturc's answer his #5 about passing data between contructors probably could use a little explanation. This is in overloading constructors and is the one case where use of this is mandatory. In the following example we can call the parameterized constructor from the parameterless constructor with a default parameter.
class MyClass {
private int _x
public MyClass() : this(5) {}
public MyClass(int v) { _x = v;}
}
I've found this to be a particularly useful feature on occasion.
I got in the habit of using it liberally in Visual C++ since doing so would trigger IntelliSense ones I hit the '>' key, and I'm lazy. (and prone to typos)
But I've continued to use it, since I find it handy to see that I'm calling a member function rather than a global function.
I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...
I pretty much only use this when referencing a type property from inside the same type. As another user mentioned, I also underscore local fields so they are noticeable without needing this.
I use it only when required, except for symmetric operations which due to single argument polymorphism have to be put into methods of one side:
boolean sameValue (SomeNum other) {
return this.importantValue == other.importantValue;
}
[C++]
this is used in the assignment operator where most of the time you have to check and prevent strange (unintentional, dangerous, or just a waste of time for the program) things like:
A a;
a = a;
Your assignment operator will be written:
A& A::operator=(const A& a) {
if (this == &a) return *this;
// we know both sides of the = operator are different, do something...
return *this;
}
this on a C++ compiler
The C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:
using the mother class' method if you did not overloaded it in the child class.
promoting a value of a type into another type
But sometimes, You just don't want the compiler to guess. You want the compiler to pick-up the right symbol and not another.
For me, those times are when, within a method, I want to access to a member method or member variable. I just don't want some random symbol picked up just because I wrote printf instead of print. this->printf would not have compiled.
The point is that, with C legacy libraries (§), legacy code written years ago (§§), or whatever could happen in a language where copy/pasting is an obsolete but still active feature, sometimes, telling the compiler to not play wits is a great idea.
These are the reasons I use this.
(§) it's still a kind of mystery to me, but I now wonder if the fact you include the <windows.h> header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace
(§§) realizing that "you need to include a header, but that including this header will break your code because it uses some dumb macro with a generic name" is one of those russian roulette moments of a coder's life
'this.' helps find members on 'this' class with a lot of members (usually due to a deep inheritance chain).
Hitting CTRL+Space doesn't help with this, because it also includes types; where-as 'this.' includes members ONLY.
I usually delete it once I have what I was after: but this is just my style breaking through.
In terms of style, if you are a lone-ranger -- you decide; if you work for a company stick to the company policy (look at the stuff in source control and see what other people are doing). In terms of using it to qualify members, neither is right or wrong. The only wrong thing is inconsistency -- that is the golden rule of style. Leave the nit-picking others. Spend your time pondering real coding problems -- and obviously coding -- instead.
I use it every time I can. I believe it makes the code more readable, and more readable code equals less bugs and more maintainability.
When you are many developers working on the same code base, you need some code guidelines/rules. Where I work we've desided to use 'this' on fields, properties and events.
To me it makes good sense to do it like this, it makes the code easier to read when you differentiate between class-variables and method-variables.
It depends on the coding standard I'm working under. If we are using _ to denote an instance variable then "this" becomes redundant. If we are not using _ then I tend to use this to denote instance variable.
I use it to invoke Intellisense just like JohnMcG, but I'll go back and erase "this->" when I'm done. I follow the Microsoft convention of prefixing member variables with "m_", so leaving it as documentation would just be redundant.
1 - Common Java setter idiom:
public void setFoo(int foo) {
this.foo = foo;
}
2 - When calling a function with this object as a parameter
notifier.addListener(this);
There is one use that has not already been mentioned in C++, and that is not to refer to the own object or disambiguate a member from a received variable.
You can use this to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.
template <typename T>
struct base {
void f() {}
};
template <typename T>
struct derived : public base<T>
{
void test() {
//f(); // [1] error
base<T>::f(); // quite verbose if there is more than one argument, but valid
this->f(); // f is now an argument dependent symbol
}
}
Templates are compiled with a two pass mechanism. During the first pass, only non-argument dependent names are resolved and checked, while dependent names are checked only for coherence, without actually substituting the template arguments.
At that step, without actually substituting the type, the compiler has almost no information of what base<T> could be (note that specialization of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent call f that seems just natural to the programmer is a symbol that the compiler must find as a member of derived or in enclosing namespaces --which does not happen in the example-- and it will complain.
The solution is turning the non-dependent name f into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (base<T>::f --adding the base<T> makes the symbol dependent on T and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.
The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a this-> before the symbol. As the template class you are implementing does depend on an argument (it inherits from base<T>) this-> is argument dependent, and we get the same result: this->f is checked in the second round, after template parameter substitution.
You should not use "this" unless you absolutely must.
There IS a penalty associated with unnecessary verbosity. You should strive for code that is exactly as long as it needs to be, and no longer.
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 6 years ago.
Improve this question
So i have a situation where i need different amounts of arguments for a function depending on the end result i desire.
I am new to C# and have heard about overloading the function which is not something i have seen before (i started in JavaScript).
But it looks bit dirty, like not a good practice to do even though it does work. Is it generally not a good idea to use overloaded functions, i could probably do an alternative with more work but overloads do make life easier.
It just feels very uncomfortable having more than one method with the same name. Are these considered standard features and acceptable code practice ? Or could it lead to some messy problems in the future that my inexperience does not know about yet and thus i should avoid it ?
Function overloads.
Named actually method overloading. C# does not have a direct distinction to methods which return a value and those that don't. Hence method.
But it looks bit dirty
It is a key component to the language which is a common practice and definitely not frowned upon.
like not a good practice to do even though it does work.
The idea is to provide different variants for a consumer. One consumer may only have X type to use while only Y type is offered. By offering more, the library, and/or instance is more flexible. Plus it lessons failure points by having the consumer convert data to get it into the method.
(i started in JavaScript).
Don't try to program in the style of language which one is accustomed to. Use the specific features of any new language as designed. By trying to do Java in C# or Ruby in C# is foolish. All languages have their design points...program to the language, not to a style of programming.
just feels very uncomfortable having more than one method with the same name.
Coming from a language which is not type safe, that is an understandable reaction. But keep in mind that the compiler is enforcing safety so that widget X is only matched with widget X; it is a true feature and not a gimmick.
Frankly when I see code which does not provide multiple overloads, I view it as either laziness of the developer or some god awful time crunch, hence rushed code.
Don't go overboard...simply provide enough overloads to make the class useable by a majority of consumers.
Or could it lead to some messy problems in the future
If one is not consistent, possibly yes.
So be consistent in the placement of the variables. If an int starts the method, the other method should also start with that same int; if offered. Don't mix the order.
Consider the following class:
public class MyClass
{
public void MyMethod(int a, object b)
{
}
}
If someone else calls your class like this:
new MyClass().MyMethod(1, 1);
And then in a future version of your assembly you add an innocent overload:
public class MyClass
{
public void MyMethod(int a, object b)
{
}
public void MyMethod(object a, int b)
{
}
}
That someone else's code will not compile against the new assembly.
You are correct that method overloading can introduce problems... however it is not always problematic.
Suppose the simple case - you have a method that operates on one Type - T. If you are tempted to add a method overload to handle a second Type U, consider what interfaces and base classes T and U might have in common (including T or U extending one another). If there is a common Type consider making that the argument type at design time (if that's specific enough). If not, then you may need a method overload. A good contrived example might be a method that returns the square of a number. There is no common abstraction for Type's that have an * operator (which you can write your own in C#). So you'd have to make (2) methods to handle an int and a double:
public int SquareMe(int x) { return x * x; }
public double SquareMe(double x) { return x * x; }
If, however, you found yourself wanting to make a method operating on List<T>, IEnumerable<T>, and T[], you may be better off writing the method to accept an IEnumerable<T> (and just calling ToArray() on it immediately to prevent the IEnumerable from expanding multiple times if your code needs it multiple times - if you're just foreach'ing it once, there's no need to expand it) this way you're left with only (1) method to write tests for. Every method, particularly on publicly consumed API's is more to maintain, document, test, automate, etc. Simpler is usually better (but complexity has its place, too). It's difficult to give an algorithm for design of API's (if there was an existing algorithm for such a thing, we could just have the design generated as the output from some hypothetical program, yes?)
When it comes to designing classes and interfaces for public consumption you should be very careful about method overloading (and your entire API, in general - method overloading introducing subtle breaking changes is just one thing to think about - almost any change could be a breaking change). If your API used by everyone, such as Microsoft, all changes to API's have to be very well thought-out and have minimum to 0 breaking changes.
If it's for "internal" use (and you can detect compilation breaks at build time) then if the compiler's happy, method overloading shouldn't be too big of a deal in and of itself. That being said - someone might call a different overload by accident because of what C# will choose. It's probably more important to have explicit method names (Microsoft recommends spelling things out in C#, generally) that intuitively (i.e. subjectively) match the content of what the method does than the concern of overloading.
Like other things, this language features is a trade off between being explicit and implicit and whether or not it's a good idea varies on the situation; method overloading can be both used and abused. In general try to learn the existing practices, patterns and culture of a new language before developing your own style on things so that you can take advantage of everyone's successes and failures before you. Method overloading definitely has its place in C#.
So, you have a situation that would be made easier by a core feature of the language you are using... and you're concerned about that? I wouldn't worry too much.
It might be idea to make an attempt and once you're happy with it take it over to codereview.stackexchange.com to get some feedback.
If the reason for varying signatures is because 'the end result you desire' varies then that's a case for having different functions.
Overloading is helpful when you have a number of optional parameters. If you have five optional parameters it's less obvious what will happen if you specify some but not others. If you create overloads then you can provide different versions of the function with required parameters. Perhaps behind the scenes they can all call a private method with optional parameters, but that remains hidden from public use.
Why not just use an optional parameter?
void Foo (int op = 42)
{
if (x!=42)
//do something
else
}
int x = 33;
Foo();
Foo(x);
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:
In a constructor:
public Light(Vector v)
{
this.dir = new Vector(v);
}
Elsewhere
public void SomeMethod()
{
Vector vec = new Vector();
double d = (vec * vec) - (this.radius * this.radius);
}
I don't mean this to sound snarky, but it doesn't matter.
Seriously.
Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the "this" keyword to qualify access to fields. The this keyword will not help you ship on time. It's not going to reduce bugs, it's not going to have any appreciable effect on code quality or maintainability. It's not going to get you a raise, or allow you to spend less time at the office.
It's really just a style issue. If you like "this", then use it. If you don't, then don't. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer's notions of what the "most aesthetically pleasing code" should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn't like, or would have done differently. At some point some guy is going to read your code and grumble about something.
I wouldn't fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn't going to be scrutinizing how you initialize fields. He's just going to use your code, marvel at it's greatness, and then move on to something else.
There are several usages of this keyword in C#.
To qualify members hidden by similar name
To have an object pass itself as a parameter to other methods
To have an object return itself from a method
To declare indexers
To declare extension methods
To pass parameters between constructors
To internally reassign value type (struct) value.
To invoke an extension method on the current instance
To cast itself to another type
To chain constructors defined in the same class
You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties.
I only use it when absolutely necessary, ie, when another variable is shadowing another. Such as here:
class Vector3
{
float x;
float y;
float z;
public Vector3(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
Or as Ryan Fox points out, when you need to pass this as a parameter. (Local variables have precedence over member variables)
Personally, I try to always use this when referring to member variables. It helps clarify the code and make it more readable. Even if there is no ambiguity, someone reading through my code for the first time doesn't know that, but if they see this used consistently, they will know if they are looking at a member variable or not.
I use it every time I refer to an instance variable, even if I don't need to. I think it makes the code more clear.
I can't believe all of the people that say using it always is a "best practice" and such.
Use "this" when there is ambiguity, as in Corey's example or when you need to pass the object as a parameter, as in Ryan's example. There is no reason to use it otherwise because being able to resolve a variable based on the scope chain should be clear enough that qualifying variables with it should be unnecessary.
EDIT: The C# documentation on "this" indicates one more use, besides the two I mentioned, for the "this" keyword - for declaring indexers
EDIT: #Juan: Huh, I don't see any inconsistency in my statements - there are 3 instances when I would use the "this" keyword (as documented in the C# documentation), and those are times when you actually need it. Sticking "this" in front of variables in a constructor when there is no shadowing going on is simply a waste of keystrokes and a waste of my time when reading it, it provides no benefit.
I use it whenever StyleCop tells me to. StyleCop must be obeyed. Oh yes.
Any time you need a reference to the current object.
One particularly handy scenario is when your object is calling a function and wants to pass itself into it.
Example:
void onChange()
{
screen.draw(this);
}
I tend to use it everywhere as well, just to make sure that it is clear that it is instance members that we are dealing with.
I use it anywhere there might be ambiguity (obviously). Not just compiler ambiguity (it would be required in that case), but also ambiguity for someone looking at the code.
Another somewhat rare use for the this keyword is when you need to invoke an explicit interface implementation from within the implementing class. Here's a contrived example:
class Example : ICloneable
{
private void CallClone()
{
object clone = ((ICloneable)this).Clone();
}
object ICloneable.Clone()
{
throw new NotImplementedException();
}
}
Here's when I use it:
Accessing Private Methods from within the class (to differentiate)
Passing the current object to another method (or as a sender object, in case of an event)
When creating extension methods :D
I don't use this for Private fields because I prefix private field variable names with an underscore (_).
[C++]
I agree with the "use it when you have to" brigade. Decorating code unnecessarily with this isn't a great idea because the compiler won't warn you when you forget to do it. This introduces potential confusion for people expecting this to always be there, i.e. they'll have to think about it.
So, when would you use it? I've just had a look around some random code and found these examples (I'm not passing judgement on whether these are good things to do or otherwise):
Passing "yourself" to a function.
Assigning "yourself" to a pointer or something like that.
Casting, i.e. up/down casting (safe or otherwise), casting away constness, etc.
Compiler enforced disambiguation.
You should always use it, I use it to diferantiate private fields and parameters (because our naming conventions state that we don't use prefixes for member and parameter names (and they are based on information found on the internet, so I consider that a best practice))
I use it when, in a function that accepts a reference to an object of the same type, I want to make it perfectly clear which object I'm referring to, where.
For example
class AABB
{
// ... members
bool intersects( AABB other )
{
return other.left() < this->right() &&
this->left() < other.right() &&
// +y increases going down
other.top() < this->bottom() &&
this->top() < other.bottom() ;
}
} ;
(vs)
class AABB
{
bool intersects( AABB other )
{
return other.left() < right() &&
left() < other.right() &&
// +y increases going down
other.top() < bottom() &&
top() < other.bottom() ;
}
} ;
At a glance which AABB does right() refer to? The this adds a bit of a clarifier.
In Jakub Šturc's answer his #5 about passing data between contructors probably could use a little explanation. This is in overloading constructors and is the one case where use of this is mandatory. In the following example we can call the parameterized constructor from the parameterless constructor with a default parameter.
class MyClass {
private int _x
public MyClass() : this(5) {}
public MyClass(int v) { _x = v;}
}
I've found this to be a particularly useful feature on occasion.
I got in the habit of using it liberally in Visual C++ since doing so would trigger IntelliSense ones I hit the '>' key, and I'm lazy. (and prone to typos)
But I've continued to use it, since I find it handy to see that I'm calling a member function rather than a global function.
I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...
I pretty much only use this when referencing a type property from inside the same type. As another user mentioned, I also underscore local fields so they are noticeable without needing this.
I use it only when required, except for symmetric operations which due to single argument polymorphism have to be put into methods of one side:
boolean sameValue (SomeNum other) {
return this.importantValue == other.importantValue;
}
[C++]
this is used in the assignment operator where most of the time you have to check and prevent strange (unintentional, dangerous, or just a waste of time for the program) things like:
A a;
a = a;
Your assignment operator will be written:
A& A::operator=(const A& a) {
if (this == &a) return *this;
// we know both sides of the = operator are different, do something...
return *this;
}
this on a C++ compiler
The C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:
using the mother class' method if you did not overloaded it in the child class.
promoting a value of a type into another type
But sometimes, You just don't want the compiler to guess. You want the compiler to pick-up the right symbol and not another.
For me, those times are when, within a method, I want to access to a member method or member variable. I just don't want some random symbol picked up just because I wrote printf instead of print. this->printf would not have compiled.
The point is that, with C legacy libraries (§), legacy code written years ago (§§), or whatever could happen in a language where copy/pasting is an obsolete but still active feature, sometimes, telling the compiler to not play wits is a great idea.
These are the reasons I use this.
(§) it's still a kind of mystery to me, but I now wonder if the fact you include the <windows.h> header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace
(§§) realizing that "you need to include a header, but that including this header will break your code because it uses some dumb macro with a generic name" is one of those russian roulette moments of a coder's life
'this.' helps find members on 'this' class with a lot of members (usually due to a deep inheritance chain).
Hitting CTRL+Space doesn't help with this, because it also includes types; where-as 'this.' includes members ONLY.
I usually delete it once I have what I was after: but this is just my style breaking through.
In terms of style, if you are a lone-ranger -- you decide; if you work for a company stick to the company policy (look at the stuff in source control and see what other people are doing). In terms of using it to qualify members, neither is right or wrong. The only wrong thing is inconsistency -- that is the golden rule of style. Leave the nit-picking others. Spend your time pondering real coding problems -- and obviously coding -- instead.
I use it every time I can. I believe it makes the code more readable, and more readable code equals less bugs and more maintainability.
When you are many developers working on the same code base, you need some code guidelines/rules. Where I work we've desided to use 'this' on fields, properties and events.
To me it makes good sense to do it like this, it makes the code easier to read when you differentiate between class-variables and method-variables.
It depends on the coding standard I'm working under. If we are using _ to denote an instance variable then "this" becomes redundant. If we are not using _ then I tend to use this to denote instance variable.
I use it to invoke Intellisense just like JohnMcG, but I'll go back and erase "this->" when I'm done. I follow the Microsoft convention of prefixing member variables with "m_", so leaving it as documentation would just be redundant.
1 - Common Java setter idiom:
public void setFoo(int foo) {
this.foo = foo;
}
2 - When calling a function with this object as a parameter
notifier.addListener(this);
There is one use that has not already been mentioned in C++, and that is not to refer to the own object or disambiguate a member from a received variable.
You can use this to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.
template <typename T>
struct base {
void f() {}
};
template <typename T>
struct derived : public base<T>
{
void test() {
//f(); // [1] error
base<T>::f(); // quite verbose if there is more than one argument, but valid
this->f(); // f is now an argument dependent symbol
}
}
Templates are compiled with a two pass mechanism. During the first pass, only non-argument dependent names are resolved and checked, while dependent names are checked only for coherence, without actually substituting the template arguments.
At that step, without actually substituting the type, the compiler has almost no information of what base<T> could be (note that specialization of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent call f that seems just natural to the programmer is a symbol that the compiler must find as a member of derived or in enclosing namespaces --which does not happen in the example-- and it will complain.
The solution is turning the non-dependent name f into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (base<T>::f --adding the base<T> makes the symbol dependent on T and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.
The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a this-> before the symbol. As the template class you are implementing does depend on an argument (it inherits from base<T>) this-> is argument dependent, and we get the same result: this->f is checked in the second round, after template parameter substitution.
You should not use "this" unless you absolutely must.
There IS a penalty associated with unnecessary verbosity. You should strive for code that is exactly as long as it needs to be, and no longer.
Can someone please break down what a delegate is into a simple, short and terse explanation that encompasses both the purpose and general benefits? I've tried to wrap my head around this and it's just not sinking in.
I have a function:
public long GiveMeTwoTimesTwo()
{
return 2 * 2;
}
This function sucks. What if I want 3 * 3?
public long GiveMeThreeTimesThree()
{
return 3 * 3;
}
Too much typing. I'm lazy!
public long SquareOf(int n)
{
return n * n;
}
My SquareOf function doesn't care what n is. It will operate properly for any n passed in. It doesn't know exactly what number n is, but it does know that n is an integer. You can't pass "Haha not an integer" into SquareOf.
Here's another function:
public void DoSomethingRad()
{
int x = 4;
long y = SquareOf(x);
Console.WriteLine(y);
}
Contrary to its name, DoSomethingRad doesn't actually do anything rad. However, it does write the SquareOf(4) which is 16. Can we change it to be less boring?
public void DoSomethingRad(int numberToSquare)
{
long y = SquareOf(numberToSquare);
Console.WriteLine(y);
}
DoSomethingRad is clearly still pretty fail. But at least now we can pass in a number to square, so it won't write 16 every time. (It'll write 1, or 4, or 9, or 16, or... zzzz still kinda boring).
It'd be nice if there was a way to change what happens to the number passed in. Maybe we don't want to square it; maybe we want to cube it, or subtract it from 69 (number chosen at random from my head).
On further inspection, it seems as though the only part of SquareOf that DoSomethingRad cares about is that we can give it an integer (numberToSquare) and that it gives us a long (because we put its return value in y and y is a long).
public long CubeOf(int n)
{
return n * n * n;
}
public void DoSomethingLeet(int numberToSquare)
{
long y = CubeOf(numberToSquare);
Console.WriteLine(y);
}
See how similar DoSomethingLeet is to DoSomethingRad? If only there was a way to pass in behavior (DoX()) instead of just data (int n)...
So now if we want to write a square of a number, we can DoSomethingRad and if we want to write the cube of a number, we can DoSomethingLeet. So if we want to write the number subtracted from 69, do we have to make another method, DoSomethingCool? No, because that takes too damn much typing (and more importantly, it hinders our ability to alter interesting behavior by changing only one aspect of our program).
So we arrive at:
public long Radlicious(int doSomethingToMe, Func<int, long> doSomething)
{
long y = doSomething(doSomethingToMe);
Console.WriteLine(y);
}
We can call this method by writing this:
Radlicious(77, SquareOf);
Func<int, long> is a special kind of delegate. It stores behavior that accepts integers and spits out longs. We're not sure what the method it points to is going to do with any given integer we pass; all we know is that, whatever happens, we are going to get a long back.
We don't have to give any parameters to SquareOf because Func<int, long> describes behavior, not data. Calling Radlicious(77, SquareOf) just gives Radlicious the general behavior of SquareOf ("I take a number and return its square"), not what SquareOf will do to any specific integer.
Now if you have understood what I am saying, then you have already one-upped me, for I myself don't really get this stuff.
* END ANSWER, BEGIN WANDERING IDIOCY *
I mean, it seems like ints could be perceived as just really boring behavior:
static int Nine()
{
return 9;
}
That said, the line between what is data and behavior appears to blur, with what is normally perceived as data is simply boring-ass behavior.
Of course, one could imagine super "interesting" behavior, that takes all sorts of abstract parameters, but requires a ton of information to be able to call it. What if it required us to provide the source code that it would compile and run for us?
Well, then our abstraction seems to have gotten us all the way back to square one. We have behavior so abstract it requires the entire source code of our program to determine what it's going to do. This is fully indeterminate behavior: the function can do anything, but it has to be provided with everything to determine what it does. On the other hand, fully determinate behavior, such as Nine(), doesn't need any additional information, but can't do anything other than return 9.
So what? I don't know.
In the simplest possible terms, it's essentially a pointer to a method.
You can have a variable that holds a delegate type (just like you would have an int variable that can hold an int type). You can execute the method that the delegate points to by simply calling your variable like a function.
This allows you to have variable functions just like you might have variable data. Your object can accept delegates from other objects and call them, without having to define all the possible functions itself.
This comes in very handy when you want an object to do things based on user specified criteria. For example, filtering a list based on a user-defined true/false expression. You can let the user specify the delegate function to use as a filter to evaluate each list item against.
A delegate is a pointer to a method. You can then use your delegate as a parameter of other methods.
here is a link to a simple tutorial.
The question I had was 'So, why would I want to do that?' You won't really 'get it' until you solve a programming problem with them.
It's interesting that no-one has mentioned one of key benefits of delegation - it's preferable to sub-classing when you realise that inheritance is not a magic bullet and usually creates more problems than it solves. It is the basis of many design patterns, most notably the strategy pattern.
A delegate instance is a reference to a method. The reason they are useful is that you can create a delegate that is tied to a particular method on a particular instance of a type. The delegate instance allows you to invoke that method on that particular instance even if the object on which you will invoke the method has left your lexical scope.
The most common use for delegate instances like this is to support the concept of callbacks at the language level.
It simply references a method. They come in great use with working with cross threading.
Here is an example right out of my code.
//Start our advertisiment thread
rotator = new Thread(initRotate);
rotator.Priority = ThreadPriority.Lowest;
rotator.Start();
#region Ad Rotation
private delegate void ad();
private void initRotate()
{
ad ad = new ad(adHelper);
while (true)
{
this.Invoke(ad);
Thread.Sleep(30000);
}
}
private void adHelper()
{
List<string> tmp = Lobby.AdRotator.RotateAd();
picBanner.ImageLocation = #tmp[0].ToString();
picBanner.Tag = tmp[1].ToString();
}
#endregion
If you didnt use a delegate you wouldn't be able to crossthread and call the Lobby.AdRotator function.
Like others have said, a delegate is a reference to a function. One of the more beneficial uses(IMO) is events. When you register an event you register a function for the event to invoke, and delegates are perfect for this task.
In the most basic terms, a delegate is just a variable that contains (a reference to) a function. Delegates are useful because they allow you to pass a function around as a variable without any concern for "where" the function actually came from.
It's important to note, of course, that the function isn't being copied when it's being bundled up in a variable; it's just being bound by reference. For example:
class Foo
{
public string Bar
{
get;
set;
}
public void Baz()
{
Console.WriteLine(Bar);
}
}
Foo foo = new Foo();
Action someDelegate = foo.Baz;
// Produces "Hello, world".
foo.Bar = "Hello, world";
someDelegate();
In most simplest terms, the responsibility to execute a method is delegated to another object. Say the president of some nation dies and the president of USA is supposed to be present for the funeral with condolences message. If the president of USA is not able to go, he will delegate this responsibility to someone either the vice-president or the secretary of the state.
Same goes in code. A delegate is a type, it is an object which is capable of executing the method.
eg.
Class Person
{
public string GetPersonName(Person person)
{
return person.FirstName + person.LastName;
}
//Calling the method without the use of delegate
public void PrintName()
{
Console.WriteLine(GetPersonName(this));
}
//using delegate
//Declare delegate which matches the methods signature
public delegate string personNameDelegate(Person person);
public void PrintNameUsingDelegate()
{
//instantiate
personNameDelegate = new personNameDelegate(GetPersonName);
//invoke
personNameDelegate(this);
}
}
The GetPersonName method is called using the delegate object personNameDelegate.
Alternatively we can have the PrintNameUsingDelegate method to take a delegate as a parameter.
public void PrintNameUsingDelegate(personNameDelegate pnd, Person person)
{
pnd(person);
}
The advantage is if someone want to print the name as lastname_firstname, s/he just has to wrap that method in personNameDelegate and pass to this function. No further code change is required.
Delegates are specifically important in
Events
Asynchronous calls
LINQ (as lambda expressions)
If you were going to delegate a task to someone, the delegate would be the person who receives the work.
In programming, it's a reference to the block of code which actually knows how to do something. Often this is a pointer to the function or method which will handle some item.
In the absolute most simplest terms I can come up with is this: A delegate will force the burdens of work into the hands of a class that pretty much knows what to do. Think of it as a kid that doesn't want to grow up to be like his big brother completely but still needs his guidance and orders. Instead of inheriting all the methods from his brother (ie subclassing), he just makes his brother do the work or The little brother does something that requires actions to be taken by the big brother. When you fall into the lines of Protocols, the big brother defines what is absolutely required, or he might give you flexibility to choose what you want to make him do in certain events (ie informal and formal protocols as outlined in Objective-C).
The absolute benefit of this concept is that you do not need to create a subclass. If you want something to fall in line, follow orders when an event happens, the delegate allows a developed class to hold it's hand and give orders if necessary.