C#: Should Object Variables Be Assigned to Null

C#: should object variables be assigned to null?

No, and that could in fact be dangerous and bug-prone (consider the possibility that someone might try to use it later on, not realizing it had been set to null). Only set something to null if there's a logical reason to set it to null.

Declaring an object of a class as null

It depends; if you declare a field, e.g.

  public class MyClass {
// objDEntr will be initialized by null
Directory objDEntr;
// the initialization is redundant here
Directory objDEntry2 = null;
...

there's no difference, since fields are initialized by their default values and null is the default value for reference types. However, local variables are not initialized by default; so

  public static void MyMethod() {
// objDEntry contains trash, must be initialized further
Directory objDEntry;
// objDEntry2 is null
Directory objDEntry2 = null;
...

in the "Example 1" objDEntry contains trash, while in the "Example 2" objDEntry is properly initialized and contains null.

Should we set variables to null, false and create new objects when initializing?

Everything except the array list is unneeded.

Fields are automatically initialized with their respective default value before the code inside the constructor is executed.

This code is equivalent:

public class CEConnection 
{
private IDomain domain;
private IObjectStoreSet ost;
private ArrayList osNames;
private String domainName;
private bool isCredentialsEstablished;

// Constructor
public CEConnection()
{
osNames = new ArrayList();
}

Is there any reason to set an object to null in the finally block?

This is dependent on scope.

In your given example, o is only defined within the scope of the property. So it will be useless. However, say o was within the scope of the class. Then it MIGHT make sense to denote the state of o.

As it is currently, it is NOT needed.

Why to assign null before initialize object in C#

The only point in doing this would be if the MediaCaptureInitializationSettings constructor could throw an exception, and you wanted to make sure that in that case the variable didn't still have a reference to an "old" object. That's pretty rarely useful, in my experience. (If a method like this throws an exception, I'd try to avoid using the object it was initializing...)

I'd recommend doing all of this with an object initializer:

_captureInitSettings = new MediaCaptureInitializationSettings
{
AudioDeviceId = "",
VideoDeviceId = _deviceList.Count > 0 ? _deviceList[0].Id : "",
StreamingCaptureMode = StreamingCaptureMode.AudioAndVideo,
PhotoCaptureSource = PhotoCaptureSource.VideoPreview
};

This has two benefits:

  • It's simpler code, IMO... much less repetition
  • It only sets the variable's value if the whole object initializer completes. If setting one property fails, you don't end up with a reference to a half-initialized object.

Do I need to null out an object reference in C# before the method ends?

Generally you don't need to worry about object references once they have gone out of scope - the garbage collector will clear up.

However, if you are using an object whose class implements the IDisposable interface then you need to make sure that it disposes of any unmanaged resources by either explicitly calling the IDisposable.Dispose() method or by wrapping its usage in a using block.

Look up IDisposable in the MSDN for further explanation.

What happens to the original data if i set a variable to null? c#

The variable in your precise example is not longer referenced, so it can be collected by the Garbage Collector. I can guarantee you it will run - even on exceptions - but not when it will run. For most cases this is not a problem.

If you already copied the reference to another variable, it is simply no longer referenced under fruits - but still under any other variable you assigned it too. The GC can not work if at there is still a strong reference to the instance

If you have some unamanged resource that needs timely freeing (any Network or File Handles), that is what the IDisposeable pattern and using blocks are there for.

What does assigning variable to null do?

The C# language prevents the use of a local until it has been definitively assigned a value. In this example the compiler doesn't understand the semantics of Split and has to assume that strArr can be an empty collection and hence the body of the loop could potentially not execute. This means from a definitive assignment perspective the foreach doesn't assign match a value. Hence it's still unassigned when you get to WriteLine

By changing the declaration to string match = null the value is marked as definitely assigned from the very start. The loop calculation hence doesn't matter



Related Topics



Leave a reply



Submit