warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.


Question: What does Visual Studio Warning entail: " warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context."


Login to See the Rest of the Answer

Answer:
This tells you that you are using a nullable annotation wrong, for example, if you have defined your method as

function myFunc(string? someString = "default"){

//This is wrong, as someString is assigned to the value of default

}

However, write your function like this:

function myFunc(string someString){

var lengthOfString = someString?.Length; //This will first check if someString is null or not.

//This is correct as someString might be null, a caller might not pass in a value for someString therefore C# 9 will check to see 
//if the value is null or not.

}

function myFunc(string someString){

var lengthOfString = someString?.Length; //This will first check if someString is null or not.

//This is correct as someString might be null, a caller might not pass in a value for someString therefore C# 9 will check to see 
//if the value is null or not.

}

Or you could write your function like this:

function myFunc(string someString){

//This will throw an error if someString has no value. This is a tredition way of writting function with paremeter, however as 

//a Developer, you should never trust input from a caller, always do some massage on the input values to catch for errors.

}






© 2024 - ErnesTech - Privacy
E-Commerce Return Policy