Link to home
Start Free TrialLog in
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.
Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

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

ASKER

Hey Chinmay,

How can understand is it managed or not managed object?
ASKER CERTIFIED SOLUTION
Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Skale

ASKER

Thank you Chinmay :)
You are welcome :)