Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set C# object to null itself [closed]

Tags:

c#

null

In C++, it is possible to delete this and set its own reference to null.

I want to set an object instance to null itself.

public class Foo
{

    public void M( )
    {
       // this = null; // How do I do this kind of thing?
    }
}
like image 892
user1924210 Avatar asked Dec 22 '12 22:12

user1924210


People also ask

What is sets in C?

Sets are associative containers that store unique elements. A stored element must be unique because it is identified with the value itself. Once the elements are inserted in the set, they cannot be modified; however, they can be inserted or removed from the container.

Where do I type C language?

A C program source code can be written in any text editor; however the file should be saved with . c extension.


3 Answers

this is actually just a special name given to the parameter, arg0, in an instance method. Setting it to null is not allowed:

  1. you cannot ever change this for instance methods on a class
  2. you can change this for instance methods on a struct, but you can't assign null

The reason for 1. is that it would not be useful:

  • the parameter arg0 is by-val (not by-ref) on class instance methods, so the method's caller won't notice the change (for completeness: arg0 is by-ref on struct instance methods)
  • it won't really change memory management in any way:
    • setting something to null does not delete it; the GC handles that
    • if there are external roots holding a reference to the object, they will still be holding a reference to the object
    • if you are worried about the edge-case of the parameter being the last root to the object, then just exit the method

So basically, that syntax is not allowed, because it doesn't do what you want. There is no C# metaphor for what you want.

like image 106
Marc Gravell Avatar answered Oct 05 '22 23:10

Marc Gravell


This is not possible in .NET. You cannot set the current instance to null from within the object itself. In .NET the current instance (this) is readonly, you cannot assign a value to it. And by the way that's not something you would even need in .NET.

like image 26
Darin Dimitrov Avatar answered Oct 06 '22 01:10

Darin Dimitrov


In C++ delete this frees the memory of the object. There is no equivalent to that in C# (or any other .NET language). Although it is allowed in C++ I don't think it's a good practice. At least you have to be very careful.

.NET uses garbage collection instead to free memory. Once an object isn't referenced any more and cannot be accessed from anywhere in your code the garbage collector can eventually free the memory (and the garbage collector is careful). So just lean back and let the garbage collector do its work.

like image 26
pescolino Avatar answered Oct 06 '22 01:10

pescolino