Why to assign null before initialize object in C#

I'm following a tutorial on how to use capture video using the Windows MediaCapture API on Windows Phone and on the code examples, some of the variables are set to null just before assigning a new instance.

private void InitCaptureSettings() {
    _captureInitSettings = null;
    _captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
    _captureInitSettings.AudioDeviceId = "";
    _captureInitSettings.VideoDeviceId = "";
    _captureInitSettings.StreamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.AudioAndVideo;
    _captureInitSettings.PhotoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.VideoPreview;

    if (_deviceList.Count > 0) {
        _captureInitSettings.VideoDeviceId = _deviceList[0].Id;
    }
}

Is there any reason why this should be done?

Thanks

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow