Trying to wrap my head around byte arrays that are produced by Socket.ReceiveFrom(Byte[], EndPoint) and later used in Guid Constructor (Byte[]).

var data = new byte[16];
var length = socket.ReceiveFrom(data, ref remoteEndpoint);
if(length == 16)
    var guid = new Guid(data);

Is it safe to assume that if socket.ReceiveFrom(...) did not produce an exception, new Guid(data) will never fail? Basically, is there ever a possibility that ReceiveFrom produces byte arrays that cannot be made into guids, without throwing an exception? Or do I have to validate the received byte array first?

1

There are 1 best solutions below

4
On

This has nothing to do with where the data came from. How is Guid supposed to know the data came from a socket?

Any bytes are valid Guids, at least regarding the validation rules that Guid uses. This code will never throw:

if(length == 16)
    var guid = new Guid(data);

Guids do have some structure according to some Guid standard I believe but that structure is almost never being used by code. It has no practical impact. I do not know of a single system that would misbehave given badly structured guids.