When assigning a default value to a uint
parameter in a C# method argument, as shown in the first code block below, I am presented with the message "A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'uint'", whereas when assigning an int to a uint variable in the method body it is fine.
The code does compile; the warning is provided by means of the red, squiggly underlining in Visual Studio 2010.
void GetHistoricData(uint historyLength = 365)
{
uint i = 365; // this is valid
}
This is easily resolved by by using 365U in place of 365, thus:
void GetHistoricData(uint historyLength = 365U)
{
// method body
}
I am finding it really difficult to find a good explanation of why it is invalid to assign an int
to the uint
in the parameter when it is valid to do so elsewhere. Can anyone help me with the 'light-bulb' moment I am trying to find?
In other words, null can be cast to Integer without a problem, but a null integer object cannot be converted to a value of type int.
The String class in the System namespace provides the IsNullOrEmpty() method to check if a string is null or an empty string(""). This is a handy method to validate user input. IsNullOrEmpty() takes a string as an input and returns a Boolean value that depends on whether or not the string is null or empty.
In C#, we can use the IsDigit() method to check if a character is numeric or a digit. The IsDigit() method can be used on a single character or on a string. In the case of a string, we have to specify the index position of the character in the string.
It compiles for me, with compiler versions of both 4.0.30319.1 and 4.0.30319.17379.
If you're using an older version or a different compiler (e.g. a Mono one) then I suspect it's simply a bug.
EDIT: If it's compiling fine (and I can't provoke a warning at all from the compiler) then I suspect it's some plug-in, such as ReSharper. (Not that I'm seeing it in ReSharper either...)
I can't reproduce this in VS2010.
I would suggest that you do update the code to the one without the warning, just for the sake of readability - but it's still valid code without the change.
Red underlining usually means you can not compile. The code analyzer on VS sometimes bugs out, producing false error messages and warnings, that still compile. Restarting VS usualy gets rid of them.
Considering that you're making a cast, so possibly also truncating the value, I presume, Visual Studio only warns you about a fact of potential problem could happen and invites you to make that cast esplicit. Especially if we are talking about default parameters, the default value should be clearly specified. Instead in case non esplicit cast, there is always a space on doubts, on what the cast value would be like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With