I am learning value types in C# and I noticed this:
when you hover over the value of a declared short, It says that It is a 32-bit int. I know that a short is a 16-bit int. Why isn't It recognizing It as an int, or maybe It does?
CodePudding user response:
you are hovering over the value (32000) which is an int
/System.Int32
literal. There isn't a suffix for short to make a literal short. The compiler will do some gymnastics to ensure that it will fit. For instance, this should not compile.
int max = int.MaxValue;
short aShort = max;
CodePudding user response:
You should try to separate the declaration from the assignment of values
-- declare -- assign
| |
short uwuhebfuyg = 3200;
Note that the declaration should be able to stand on its own, as the following is valid code
short uwuhebfuyg;
which could be assigned a value zero, one or more times later in code.
uwuhebfuyg = 100;
uwuhebfuyg = 16383;
Here the compiler interprets the digits as an integer and tries to fit it inside a short data type.
CodePudding user response:
Here's an explicit example of what's happening with the implicit conversion you're asking about.
Try this struct
:
public struct NoMoreThanTwoCharacterString
{
public string Value;
public NoMoreThanTwoCharacterString(string source)
{
this.Value = source.Length <=2 ? source : source.Substring(0, 2);
}
public static implicit operator NoMoreThanTwoCharacterString(string source)
=> new NoMoreThanTwoCharacterString(source);
}
It defines a struct that holds a string that must not be longer than 2 characters. It defines an implicit operator
than will allow any string
to be assigned to a variable of type NoMoreThanTwoCharacterString
.
You could use this type like this:
NoMoreThanTwoCharacterString x = "Hello";
Console.WriteLine(x.Value);
That writes out He
to the console.
The type on the left of the =
can be different to the type on the right. The implicit operator
allows for the assignment to work, but in doing so it may need change the incoming value.