dotnet / dotnet/roslynator

Request: Unwrap Nullable / Wrap with Nullable

Open
#416 0 comments 0 reactions 0 assignees View on GitHub
Area-Refactorings Feature Request
Dominant language
C#
Stars
3.5k
Forks
294
Avg merge
2h 30m
Merged PRs (30d)
4

Description

## Unwrap Nullable
I occasionally find code that uses Nullable types when it doesn't need to do so. Unwrapping Nullable by hand can be somewhat tedious.
#### Before
```csharp
private static string CalculateMidpoint(string startTime, string endTime)
{
DateTime? windowStartTime = DateTime.ParseExact(startTime, "HHmm", null);
DateTime? windowEndtime = DateTime.ParseExact(endTime, "HHmm", null);

windowStartTime = windowStartTime.Value.AddMinutes(-windowStartTime.Value.Minute);
windowEndtime = windowEndtime.Value.Minute == 0 ? windowEndtime : windowEndtime.Value.AddMinutes(60 - windowEndtime.Value.Minute);

TimeSpan half = CalculateMidpoint(windowStartTime, windowEndtime);
return (windowStartTime.Value + half).ToString("HHmm");
}
```
#### After
```csharp
private static string CalculateMidpoint(string startTime, string endTime)
{
DateTime windowStartTime = DateTime.ParseExact(startTime, "HHmm", null);
DateTime windowEndtime = DateTime.ParseExact(endTime, "HHmm", null);

windowStartTime = windowStartTime.AddMinutes(-windowStartTime.Minute);
windowEndtime = windowEndtime.Minute == 0 ? windowEndtime : windowEndtime.AddMinutes(60 - windowEndtime.Minute);

TimeSpan half = CalculateMidPoint(windowStartTime, windowEndtime);
return (windowStartTime + half).ToString("HHmm");
}
```
## Reverse: Wrap with Nullable
The ability to promote a local variable from a standard struct/ValueType to a Nullable<> would also be handy. The user should do this with the intention of adding code that would make use of a null. In this case, not having to chase down all of the existing usage to add `.Value` everywhere would be nice. The Before/After examples could be flipped from the above code samples depicting unwrap.

Contributor guide

Open the contributing guide

Research direction

The issue provides C# before/after examples for unwrapping and wrapping Nullable values, but names no files, tests, or entry points. Start by locating the relevant nullable analysis and code-fix areas in Roslynator. Done means both transformations work as described and are covered by appropriate tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.