Avatar of Skale
Skale
 asked on

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

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.
C#

Avatar of undefined
Last Comment
Chinmay Patel

8/22/2022 - Mon
Chinmay Patel

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.
Skale

ASKER
Hey Chinmay,

How can understand is it managed or not managed object?
ASKER CERTIFIED SOLUTION
Chinmay Patel

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Skale

ASKER
Thank you Chinmay :)
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Chinmay Patel

You are welcome :)