ChopperCharles ChopperCharles - 4 months ago 45
C# Question

Is it possible for Regex.Match() to return null? (C# .Net framework 3.5?)

Is it possible that regex.Match in the (much simplified) code below can ever return null?

Regex regex = new Regex(pattern);
Match m = regex.Match(input);

My static analysis tool complains without a null check on m, but I'm thinking it's not actually necessary. It'd be nice to remove the null check so my code coverage is 100% for the method it's contained in.



Sam Sam

Documentation is your friend here:

Return Value

Type: System.Text.RegularExpressions.Match

An object that contains information about the match.

Microsoft is telling you that it will only return a Match object (not null), which means you can rightfully assume this to be true.

There is a chance, according to the docs, that it throws an exception (ArgumentNullException or RegexMatchTimeoutException), though.