Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to assign null before initialize object in C#

Tags:

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

like image 419
GLlompart Avatar asked Mar 11 '15 14:03

GLlompart


1 Answers

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.
like image 106
Jon Skeet Avatar answered Oct 05 '22 05:10

Jon Skeet