0

I want to know, Need I check variables to null in constructors .Net? For example:

public SftpRepository(ISftpConfig sftpConfig)
{
    if (sftpConfig is null)
    {
        throw new ArgumentNullException(nameof(sftpConfig));
    }

    _baseUrl = sftpConfig.BaseUrl);
    _sftpClient = new SftpClient(
        sftpConfig.Host,
        sftpConfig.Port,
        sftpConfig.Username,
        sftpConfig.Password);
}
  • This question is ultimately soliciting opinions, I'm afraid. – DiplomacyNotWar May 28 '22 at 09:29
  • Does this answer your question? [When is it right for a constructor to throw an exception?](https://stackoverflow.com/questions/77639/when-is-it-right-for-a-constructor-to-throw-an-exception). Yours is a _one-stage_ construction so _["One-stage constructors should throw if they fail to fully initialize the object. If the object cannot be initialized, it must not be allowed to exist, so the constructor must throw."](https://stackoverflow.com/a/77705/585968)_ – MickyD May 28 '22 at 09:58

1 Answers1

3

Yes, it's good practice to do so. Even if nullability annotations are enabled, you should still do a null test in a constructor, because Nullability checks do not prevent passing null.

Also, it's better to have this null check and an explicit ArgumentNullException than to rely that (in your case) a NullReferenceException will be thrown anyway.

PMF
  • 10,988
  • 2
  • 23
  • 41