-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Description
Background and motivation
A few more helper methods that can replace a lot of boring and copy-paste if checks in dotnet/runtime and user code as well.
I believe that this one and #69590 will cover all possible helpers 😸
API Proposal
public class FileNotFoundException
{
public static void ThrowIfNotExists([NotNull] string? path) {}
}
public class DirectoryNotFoundException
{
public static void ThrowIfNotExists([NotNull] string? path) {}
}
public class NotSupportedException
{
public static void ThrowIf(bool condition, string? message = null) {}
}
public class InvalidOperationException
{
public static void ThrowIf(bool condition, string? message = null) {}
}API Usage
FileNotFoundException
runtime/src/libraries/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.cs
Lines 274 to 277 in 6ca8c9b
| if (!File.Exists(fileName)) | |
| { | |
| throw new FileNotFoundException(fileName); | |
| } |
I also saw weird code like this
public void SomeIORelatedMethod(string path)
{
if (!new FileInfo(path).Exists)
throw new FileNotFoundException();
}DirectoryNotFoundException exactly same as previous, File.Exists -> Directory.Exists, new FileInfo -> new DirectoryInfo
NotSupportedException
| get | |
| { | |
| if (!CanSeek) | |
| throw new NotSupportedException(SR.SeekNotSupported); | |
| return _stream.Length; | |
| } |
There are 15 more absolutely same checks only in this file. Widely used in Stream and Http related classes
InvalidOperationException
I think the only Enumerator types in /runtime have more than thousand lines of code like this
runtime/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/List.cs
Lines 1152 to 1155 in 6ca8c9b
| if (_index == 0 || _index == _list._size + 1) | |
| { | |
| ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); | |
| } |
Alternative Designs
No response
Risks
No response