ServiceElementCreateNumericalServiceElement Method

Create an instance of ServiceElement but internally converting the numeric value to the required type.

Definition

Namespace: InTheHand.Net.Bluetooth.Sdp
Assembly: InTheHand.Net.Bluetooth (in InTheHand.Net.Bluetooth.dll) Version: 4.0.32+5cdf1cfd21064ea31c5de33d160200ca1c4bc218
C#
public static ServiceElement CreateNumericalServiceElement(
	ElementType elementType,
	Object value
)

Parameters

elementType  ElementType
The type of the element as an ElementType. Should be one of the UnsignedInteger/TwosComplementInteger types.
value  Object
The value for the new element, should be a numerical type.

Return Value

ServiceElement
The new element.

Remarks

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

C#
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);
The last example failing with:
 
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)

Exceptions

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.

See Also