When a class has an internal variable, should it be passed to methods internally, or should the method 'know' about it?
Eg
int _someid;
private void MyFunction(int ID)
{ use ID ... }
or
private void MyFunction()
{ use _someid ... }
No, you should use the second example.
If this method is meant to only use the member variable, then the second example is correct.
If your intentions are to use this method with other passed in values, from say other methods within the class, or maybe some external calls, then the first option will do.
The method should 'know' about it. This is a large part of the point of having fields in the first place.
Well, it just depends I guess. Do you ever want to call this method with anything but _someId as the parameter? If so, use the first example. If not, use the second.
The member variable is scoped to the class. So member functions 'know' about it. So assuming your member function is not static, your second example is correct.
Related
for example, there are bunch of overloads of method:
public void MyLongFunctionName(string arg1,...) ...
public void MyLongFunctionName(int arg1,...) ...
//.... many different argument types
To make a shortcut of that long function, i used i.e. my() :
public void my(string arg1,...) ...
public void my(int arg1,...) ...
....
however, is something like this possible to make my() as a shortcut of MyLongFunctionName() , without defining bunch of my() methods (like above) ?
for example, in PHP you can copy function, like :
$my = MyLongFunctionName(arg1, arg2....);
//execute
$my(arg1, arg2....)
P.S. Note to all downvoters and duplicate-markers:
this topic is not duplicate, because that referred topic doesnt answer the question at all. It executes plain function, and even says, that it is not alias at all:
so, that topic doesnt solve the problem. instead, I want to mirror(a.k.a. ALIAS) whole overloads of specific method with i.e. my(), which can accept variation of parameters. so, please stop mindless downvotings of what you dont read.
I'm afraid what you are asking is not possible.
What you want is a kind of delegate for a whole bunch of methods. It's called a method group.
A method group is a set of overloaded methods resulting from a member lookup (§7.4).
For example something.ToString is a method group. It may contain one or more methods, depending on whether ToString has overloads for this specific class.
This is a compile time construct. You cannot put a method group into a variable, like you can with a single function. You can make a delegate from a method group, but that involves getting a specific overload and transforming only that into the delegate.
I have a server where every connected client is represented by an instance of client class. This class is responsible for data processing. I always thought that when calling private function even when there are more instances of the same class, I dont need to use "this" keyword because its considered as local call, also:
if (data[1]==2 && data [3]==2)
SendAck();
But when there were more players (more client classes), sometimes the message was sent to another player and the same with other methods. All was OK when I added "this" to all methods call. Is it possible that wihout "this" it calls method from some other class?
Thanks!
EDITL: What about using public members like public dictionary in each instance and then not using this keyword /like when calling TryGetValue/?
No, this isn't possible. "this" is almost all of the time optional. A situation where you would need it would be if you have a method (for example your constructor) that takes parameters of the same name than fields of your class and you want to assign the values of these parameters to the fields, eg:
class Test
{
private string strValue;
public Test(string strValue)
{
this.strValue = strValue;
}
}
I thinks there is another problem in your code. Could you please give more details?
There isn't any difference between SendAck(); and this.SendAck();, if the method is a member of your class. You will always call the method from the instance that is calling the method.
Check what the method actually does when called, using the debugger. You will see that it is the same method, with or without the this keyword.
From C# Specification:
7.5.7 This access
…
When this is used in a primary-expression within an
instance method or instance accessor
of a class, it is classified as a
value. The type of the value is the
instance type (§10.3.1) of the class
within which the usage occurs, and
the value is a reference to the object
for which the method or accessor was
invoked.
I suspect that you have problems with multithreaded access to instances of type that represent connected clients.
How does the system know what to use when 'this' keyword is used?
Recently, I was asked this question in an interview. Having never thought about this, I replied back saying that the system will know the current context in which the flow of control is and decide the object to be used instead of this. The interviewer didn't look pleased and he moved on to the next question.
Can anyone tell me what did the interviewer may have wanted to ask and what would be the answer?
(I think this can interpreted in different ways and hence keeping this as wiki unless someone point out not to..)
Though the answers which point out that the "this" reference is essentially passed as a magic "hidden parameter" to the call are essentially correct, the full story is actually quite a bit more complicated in C# than one might think at first glance.
Reference types are straightforward; the referenced object is checked for null and then conceptually passed as an unnamed, non-variable parameter called "this". The story is complicated by value types.
Remember, value types are, by definition, passed by value -- that is, passed by making a copy of the data. Hence their name. But clearly mutable value types -- which are pure evil and should be avoided -- cannot be passed by value as the "this", because if you called a mutator, the "this" in the mutator method would be mutating the copy, not the original!
Therefore, in a value type's method call, "this" is not the value of the receiver, it is an alias to the variable representing the storage location of the receiver. We implement this by passing "this" as the managed address of the receiver, not the value of the receiver.
Now we can raise another difficulty. What if the variable storing the value being mutated is a read-only variable? Now what do we do? If you're curious, read my article on the subject and see if you can correctly answer the puzzle presented:
http://blogs.msdn.com/ericlippert/archive/2008/05/14/mutating-readonly-structs.aspx
The this keyword is a pointer to the current object. All non-static member functions of a class have access to a this pointer.
The pointer to the current object is normally made available by the compiler in a non-static member function by using a register, usually ECX. So when you write this in a non-static member function the compiler will translate that call into loading the address from ECX.
Check this simple example:
A t;
t.Test();
004114DE lea ecx,[t]
004114E1 call std::operator > (41125Dh)
Before calling the non-static member function Test() the compiler loads the register ECX with [t] (the address of variable t - will be this inside Test method).
004114DE lea ecx,[t]
And inside the function it can use ecx to obtain the address for the current object instance.
this is a hidden parameter in all methods of an object and contains a copy of the instance pointer.
Consider this class
class A {
private:
int data;
public:
void SetData(int arg) {
this->data = arg;
}
}
and this code that calls SetData():
A objA;
objA.SetData(1);
When the above code is compiled, the compiler emits something equivalent to this for the member function:
void SetData(A* this, int arg) {
this->data = arg;
}
And the calling code is converted to something like this:
A objA;
SetData(&objA, 1);
What this means is that upon compilation:
Member functions are converted to simple, global functions.
The class instance to which member functions "belong" is simply passed as the first argument to them (or rather its address is passed).
So in conclusion, what you refer to as this pointer in your code simply ends being the the first argument to the function. This is how the "system knows" which object to access through the "this" pointer.
The above example is of C++. If you for a moment forget about the CLR and the JITting and all that, what happens in C# is conceptually the same thing.
At run time "this" will resolve to the pointer to the current object, therefore "the system" will be able to call a respective method on that object.
I would have answered "It is a reference to the instance of the current class."
Dan
The compiler takes care of correctly resolving that reference at compile time. If you want to know more information about some of the techniques they use to do this, this book will tell you everything you need to know:
http://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools
in c the this pointer is an invisible pointer argument to your class.
So in essence the first argument to a class method is the pointer to the class itself. You reference it by using this.
My answer would have been "Who cares? It knows. If I ever need to find out in more detail I'll Google it."
You obviously know what the effect of using "this" would be, which surely is the important thing. For 99% of programming tasks I would have thought that the detail of how it is resolved internally is trivia.
Shematicaly compiler converts such code:
pObject->someMethod(A,B,C)
Into such code if 'someMethod' is not virtual:
someMethod(pObject,A,B,C)
Or into such code if 'someMethod' is virtual:
(*pObject->vtable[someMethodIndex]) (pObject, A,B,C)
And everywhere you place 'this' keyword first parameter is used instead of it;
Of course compiler may optimize/simplify by removing first argument and use some CPU register (normally esx) to store object's address.
The "this" operator will point to the current object. An example where the presence of a "this" operator will make a difference is this:
public class MyClass
{
int value;
public void Test(int value)
{
MessageBox.Show(value); // Will show the parameter to the function
MessageBox.Show(this.value); // Will show the field in the object
}
}
Note that the "this" operator will not change what virtual function will be called if it is overridden in a child class
public class MyClass
{
public virtual void Test() {}
public void CallTest()
{
this.Test();
}
}
public class MyClass2 : MyClass
{
public override void Test() {}
}
If you execute the following code
MyClass c = new MyClass2();
c.CallTest();
will still call the MyClass2.Test() and not MyClass.Test()
So the "this" operator simply tells you, that you are accessing something declared at class level.
I've decided to use this.variableName when referring to string/int etc.. fields.
Would that include ArrayList, ListBox etc too?
Like:
private ListBox usersListBox;
private void PopulateListBox()
{
this.usersListBox.Items.Add(...);
}
...Or not?
And what about classes?
MyClass myClass;
private void PlayWithMyClass()
{
this.myClass = new MyClass();
this.myClass.Name = "Bob";
}
?
This looks kind of odd to me.
And I don't know if I should use this.PublicProperty or only private fields.
I'm not 100% with the C# terminology, but hopefully what I said makes sense.
I used to do that sort of thing, but now I find that IDEs are pretty smart about giving me a visual indication that I'm dealing with a member variable. I only use "this" when it's necessary to distinguish the member variable from a parameter of the same name.
the this. command will allow you to call anything that is in scope in the same class as you are executing. You can access private and public variables and since everything in c# is a object calling a class is the same as calling a string.
You don't have to use this in your code if you don't want to as it is implied in c# unless a method param and a global variable are the same.
Less is more. Less text to parse is more readable.
I use this in the constructors since my parameters and member variables have the same names (I don't like marking member variables with _).
public class A
{
int a;
public A(int a)
{
this.a = a;
}
}
If your class is small enough and does one thing well, then usually you wouldn't need to add this for the sake of readability.
If you can read the whole class easily, what would be the point? It'd be more typing and clutter the code, thus possibly degrade the readability
using the 'this' keyword can be against any instance of an object. So this means u can use it to reference a class instance (eg. usersListBox, myClass, etc).
It's perfectly fine.
Some people use it to clearly explain what they are referencing so people understand that the instances are in the scope of the code and not external or part of another instance or static member elsewhere.
Finally, you can use it to reference both private and/or public properties and fields and members.
This is nothing more then a keyword pointing to the current instance. In a function, this.foo is generally the same as foo.
As msdn tells you:
The this keyword refers to the current instance of the class.
The page about the this keyword contains a lot more info.
As the this. is implicit you only need to actually use it when disambiguating between class variables and local variables of the same name.
The examples you've given would work how you've written then or like this:
private ListBox usersListBox;
private void PopulateListBox()
{
usersListBox.Items.Add(...);
}
MyClass myClass;
private void PlayWithMyClass()
{
myClass = new MyClass();
myClass.Name = "Bob";
}
it's just a matter of personal preference. If you do choose one over the other, try to be consistent.
Is there a way via System.Reflection, System.Diagnostics or other to get a reference to the actual instance that is calling a static method without passing it in to the method itself?
For example, something along these lines
class A
{
public void DoSomething()
{
StaticClass.ExecuteMethod();
}
}
class B
{
public void DoSomething()
{
SomeOtherClass.ExecuteMethod();
}
}
public class SomeOtherClass
{
public static void ExecuteMethod()
{
// Returns an instance of A if called from class A
// or an instance of B if called from class B.
object caller = getCallingInstance();
}
}
I can get the type using System.Diagnostics.StackTrace.GetFrames, but is there a way to get a reference to the actual instance?
I am aware of the issues with reflection and performance, as well as static to static calls, and that this is generally, perhaps even almost univerally, not the right way to approach this. Part of the reason of this question is I was curious if it was doable; we are currently passing the instance in.
ExecuteMethod(instance)
And I just wondered if this was possible and still being able to access the instance.
ExecuteMethod()
#Steve Cooper:
I hadn't considered extension methods. Some variation of that might work.
Consider making the method an extension method. Define it as:
public static StaticExecute(this object instance)
{
// Reference to 'instance'
}
It is called like:
this.StaticExecute();
I can't think of a way to do what you want to do directly, but I can only suggest that if you find something, you watch out for static methods, which won't have one, and anonymous methods, which will have instances of auto-generated classes, which will be a little odd.
I do wonder whether you should just pass the invoking object in as a proper parameter. After all, a static is a hint that this method doesn't depend on anything other than its input parameters. Also note that this method may be a bitch to test, as any test code you write will not have the same invoking object as the running system.
I do not believe you can. Even the StackTrace and StackFrame classes just give you naming information, not access to instances.
I'm not sure exactly why you'd want to do this, but know that even if you could do it it would likely be very slow.
A better solution would be to push the instance to a thread local context before calling ExecuteMethod that you can retrieve within it or just pass the instance.
In the case of a static method calling your static method, there is no calling instance.
Find a different way to accomplish whatever you are trying to do.
Just have ExecuteMethod take an object. Then you have the instance no matter what.
I feel like I'm missing something, here. The static method can be called from literally anywhere. There's no guarantee that a class A or class B instance will appear anywhere in the call stack.
There's got to be a better way to accomplish whatever you're trying to do.