VocaDB / ResXFileCodeGenerator

VocaDb.ResXFileCodeGenerator is a C# source generator to generate strongly-typed resource classes for looking up localized strings.

Home Page:https://www.nuget.org/packages/VocaDb.ResXFileCodeGenerator

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Make nullability optional

bastianeicher opened this issue · comments

I'd like to suggest making the nullability of the generated properties optional. I think for most use-cases it can be safely assumed the resources will always return a value (falling back to the neutral language if the thread's current language is not available).

As it is currently, I'd need to litter my code with lot's of ! everywhere I access Resources (e.g. string.Format(Resources.MyResource!, someVar) instead of string.Format(Resources.MyResource, someVar).

I also think for most use-cases it can be safely assumed the resources will always return a value, but what would be the best way? I came up with the following ideas.

  1. Use the null-forgiving operator.
public static string CreateDate => ResourceManager.GetString(nameof(CreateDate), CultureInfo)!;
  1. Return an empty string.
public static string CreateDate => ResourceManager.GetString(nameof(CreateDate), CultureInfo) ?? string.Empty;
  1. Throw an exception.
public static string CreateDate => ResourceManager.GetString(nameof(CreateDate), CultureInfo) ?? throw new InvalidOperationException();

As a workaround, you can use v1.0.2 instead of v1.0.3, because the former generates code just like option 1.

Personally, I'd go with Option 1 because:
Option 2 hides a problem in the unlikely case there is one.
Option 3 adds a (tiny) extra overhead because each resource access performs an additional if-check.

Thanks for the hint with v1.0.2! :)

I took option 1 and published v1.0.4. Now that I replaced SyntaxFactory with StringBuilder, it should be a little bit faster. Thanks for your feedback! :)