Using "this" - many instances of class, calling private method - c#

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.

Related

How I can access instance from MethodInfo

I have a method receiving a function, usually a method. From that function I can access to the method's class and other stuff using MethodInfo.
I want to be able to access the instance used, if any, when passing the function/method.
Example:
MyFunctionReceivingAMethod(new SomeClass().MethodA)
I want to access at MyFunctionReceivingAMethod to SomeClass instance from MethodA's reflection data. Is that possible?
Update:
I know I can pass the reference to the method but I wonder if its possible to get it using the funtion pointer I already have.
The reflection data in the MethodInfo class are associated with the method in general, not with any particular instance. Thus, you can't get the information you're looking for from that class.
Instead, the Delegate.Target property will return the instance associated with the received delegate (which I'm assuming is what you're looking for). According to its description on MSDN, the property returns:
The object on which the current delegate invokes the instance method, if the delegate represents an instance method; null if the delegate represents a static method.

Why do I sometimes have to pass a class by reference and other times not?

I have a method that takes List<Foobar> and Foobar as parameters. Foobar is a regular class with private variables, a constructor, and methods to operate on the data.
I modify both of the instances passed in the method but for some reason I have to pass Foobar with the ref keyword or else the changes do not stick when the method completes. I do not have to do this for the list.
I've noticed this a couple times recently in my programming. Usually when passing an instance of a class to the method, modifying it changes the instance, but sometimes it doesn't and it requires the ref keyword for changes to stick. It seems rather random in when it works. Does anyone know why this is?
If the value of a parameter change, like this:
parameter = new SomeValue();
then that change will only be seen by the caller using ref.
If instead you're changing the contents of an object which the caller passed a reference to, then that reference can be passed by value:
public void AppendHello(StringBuilder builder)
{
// This changes the data within the StringBuilder object that the
// builder variable refers to. It does *not* change the value of the
// builder variable itself.
builder.Append("Hello");
}
See my article on parameter passing for more information.
Note that if the parameter type is a struct instead of a class, then you won't be passing a copy of the reference to an object - you'll be passing the actual data itself. In that situation you'd need to use ref as well.
What do you mean by "modifying it". You can pass an object to a method and change its data, either by changing properties or adding elements to a generic list. However, you cannot change the actual object pointed to by that variable. In order to actually change, say Foobar to something else entirely, it needs to be passed by ref.

C# - Member variables passed to internal methods?

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.

How does the system know what to use when 'this' keyword is used?

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.

Can I get the calling instance from within a method via reflection/diagnostics?

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.

Categories