Is it required to set a object property null before assign a object in C#

Hakan
Hakan used Ask the Experts™
on
Hello,

I'd like to know that, is there any benefit pros/cons assign a object variable which has already existing object.

For example i have global variable MyModel with a type MyComType and it has a ObjectValue,

After a while if i changed it's value to another object with the same type; is there any cons using like this.

I think this is more related to lifetime of objects but i'd like to ask here.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
Hi Hakan,

You can do a direct assignment if it's a managed object and ideally you should let .Net Runtime take care of the rest of the stuff.

For unmanaged objects explicitly nullifying an object Or calling dispose is better suited.


Also, If you want better control over garbage collection there are other techniques you can use as well, for example you can use using block. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

Regards,
Chinmay.

Author

Commented:
Hey Chinmay,

How can understand is it managed or not managed object?
Chief Technology Ninja
Distinguished Expert 2018
Commented:
Hi Hakan,
Textbook definition:
*any object* whose life cycle is not controlled by CLR is an unmanaged object.

A bit more practical take:
*any object* that does not respect / support automatic garbage collection (i.e. after it's life cycle is over) frees up resources (for example, memory, pointers, locks) is considered Unmanaged object.
https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/unmanaged

Some common examples of unmanaged objects are
1. Database Connections
2. Network Connections
3. File System Access
4. Windows / PInvoke calls

Regards,
Chinmay.

Author

Commented:
Thank you Chinmay :)
Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
You are welcome :)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial