public static ServiceElement CreateNumericalServiceElement(
ElementType elementType,
Object value
)
Public Shared Function CreateNumericalServiceElement (
elementType As ElementType,
value As Object
) As ServiceElement
public:
static ServiceElement^ CreateNumericalServiceElement(
ElementType elementType,
Object^ value
)
static member CreateNumericalServiceElement :
elementType : ElementType *
value : Object -> ServiceElement
As noted in the constructor documentation (#ctor(ElementType, Object)) the type of the value supplied must exactly match the element's natural type, the contructor will return an error if that is not the case. This method will instead attempt to convert the value to the required type. It uses the IConvertible interface to do the conversion, for instance if the element type is Uint16 then it will cast the input value to IConvertible and call ToUInt16(IFormatProvider) on it. If the value is not convertible to the element type then an ArgumentOutOfRangeException will be thrown see below.
For instance, passing in an C# int / Visual Basic Integer to the constructor will fail for element types UInt8 etc, however by using this method it will succeed if the value is in the correct range. For example
int i = 10;
int j = -1;
// Error, Int32 not suitable for element type UInt8.
ServiceElement e0 = new ServiceElement(ElementType.UInt8, i);
// Success, Byte value 10 stored.
ServiceElement e1 = ServiceElement.CreateNumericalServiceElement(ElementType.UInt8, i);
// Error, -1 not in range of type Byte.
ServiceElement e2 = ServiceElement.CreateNumericalServiceElement(ElementType.UInt8, j);
System.ArgumentOutOfRangeException: Value '-1' of type 'System.Int32' not valid for element type UInt16.
---> System.OverflowException: Value was either too large or too small for a UInt16.
at System.Convert.ToUInt16(Int32 value)
at System.Int32.System.IConvertible.ToUInt16(IFormatProvider provider)
at InTheHand.Net.Bluetooth.ServiceElement.ConvertNumericalValue(ElementType elementType, Object value)
--- End of inner exception stack trace ---
at InTheHand.Net.Bluetooth.ServiceElement.ConvertNumericalValue(ElementType elementType, Object value)
at InTheHand.Net.Bluetooth.ServiceElement.CreateNumericalServiceElement(ElementType elementType, Object value)
at MiscFeatureTestCs.Main(String[] args)
ArgumentException | The elementType is not a numerical type. |
ArgumentOutOfRangeException | The value wasn’t convertible to the required type, e.g. if -1 is passed for element type UInt8, as shown above. |