C#: no this = no fun

Started by
2 comments, last by Daniel Miller 18 years, 9 months ago
In static classes <tt>this</tt> has no meaning (and is a compile-time error if used). However, how are you supposed to deal with this: <!–STARTSCRIPT–><!–source lang="c#"–><div class="source"><pre><span class="cpp-keyword">public</span> <span class="cpp-keyword">static</span> <span class="cpp-keyword">void</span> AddToScene(List&lt;Image&gt; images) { <span class="cpp-keyword">this</span>.images.AddRange(images); <span class="cpp-comment">//images is a static field</span> } </pre></div><!–ENDSCRIPT–> After changing a class to a static class, I encountered this problem. How can I "access" the field <tt>images</tt>? Do I have to rename the arguement?
Advertisement
I assume images is static.

try

<Name of the class>.images.AddRange(images);

[edit]
You can't use this, becuase this refers to the instance of the object being called. Since your method is static, it doesn't refer to a specific instance. So the only things it can access is other static variables and methods. There isn't any member variables avaiable.

"I can't believe I'm defending logic to a turing machine." - Kent Woolworth [Other Space]

This has no meaning in a static class because you can use the class without it being associated with an instance of that class, so 'this' wouldn't make sense in this situation because it wouldn't be associated with any object.

You also cannot declare instance members in a static class, so if you have a field images in a static class it will not compile.

You are showing a static method, so I'm going to assume you have a regular class but are trying use a static method. A static method can be called with or without an instance of the class being instantiated, so you can also not use 'this' in a static method because it might not have an instance associated with it. In this case, you can call the static method as follows: Assume you have a class named MyClass and a static method named MyStaticMethod, MyClass.MyStaticMethod();

You can also not reference non-static fields inside static methods because you might not have an instance of the class to use. With static methods you never have to instantiate an object to use them, so they can only access static fields.

I hope that helps and makes sense.

- Kevin
Quote:Original post by Rattrap
I assume images is static.

try

<Name of the class>.images.AddRange(images);

[edit]
You can't use this, becuase this refers to the instance of the object being called. Since your method is static, it doesn't refer to a specific instance. So the only things it can access is other static variables and methods. There isn't any member variables avaiable.



Right, I realize why this doesn't work. I'll try your method...

...and that's it. Actually, I feel like an idiot for not thinking of that, because that is how everything is reffered to outside of the class.

Thanks!

This topic is closed to new replies.

Advertisement