String Theory - DotNet7
In dotnet 7 strings are getting some love with a few improvements that will make devs life a little easier. Dotnet 7 introduces a new attribute for strings which gives your editor the context in which the string is to be used, this means that it can assist developers with code completion and warnings about strings that don't meet the required syntax.
To give this a concrete example you can set a string as being json with the StringSyntax attribute taking StringSyntaxAttribute.Json as the argument in the following code:
function Setup()
{
string jsonValues = @"{
""value1"":"3"
""value2"":4
}";
var intValues = ExtractValuesFrom(jsonValues);
}
private int[] ExtractValuesFrom([StringSyntax(StringSyntaxAttribute.Json)] string jsonblob)
{
var intValues = new int[]{};
//Process json and return intValues
return intValues;
}
The above code has errors in the json that without the support of the new attribute would not be triggered until run time since jsonValues is a valid string but not valid json. The new features will highlight the fact that the json is not valid and missing a "," , the line should read ""value1"":"3",
The StringSyntax attribute will not give runtime errors relating to strings, if used on an api endpoint it won't validate string values being passed in, a string is still a string and will be treated as such at runtime. It is to be used as an aid during coding for the following reason:
领英推荐
As of now (29th September 2022), using?this on Visual Studio Mac these features have not been integrated but should be coming soon.
DotNet 7 is in preview, this article the code was tested again Dotnet 7.0 RC1 running on a Mac with Visual Studio Mac 17.4 Preview
thanks to?Steve Johnson?for the string photo, found on?Unsplash