I have a class Port
representing port's number with min and max value limits.
public class Port
{
public const int MinPortNumber = 1025;
public const int MaxPortNumber = ushort.MaxValue;
private readonly int _portNumber;
private Port(int portNumber)
{
_portNumber = portNumber;
}
public static implicit operator int(Port port) => port._portNumber;
public override string ToString() => $"{_portNumber}";
public static Port FromNumber(int portNumber)
{
Validate(portNumber);
return new Port(portNumber);
}
private static void Validate(int port)
{
if (port is < MinPortNumber or > MaxPortNumber)
throw PortRangeException.NotInRange(port, MinPortNumber, MaxPortNumber);
}
}
I was trying to access it's value from another project, but on build I receive compilation error [CS1061]:
public class ServiceViewModel
{
public ServiceViewModel()
{
_port = Port.MinPortNumber;
}
[ObservableProperty]
private int _port;
}
I accessed this const in same project like
if ((int)(service.Port) is < Port.MinPortNumber or > Port.MaxPortNumber) {}
and it has worked.
So, why doesn't compiler allow me to access this const in that case?
It was my mistake.
Private field [ObservableProperty] private int _port;
generates Port
property, so it hides Port
class behind it.
Solution was to rename this field and regenerate property.
[ObservableProperty] private int _portNumber = Port.MinPortNumber;