Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to switch on a Guid in C#

So in C# the switch statement only supports integral types (not Guids), so a simple O(1) comparison table doesn't look possible.

What is the most computationally efficient way to match on a Guid

At first I thought

if(gMyGuid == new Guid("VALUE"))
else if (gMyGuid == new Guid("VALUE2")
else if (gMyGuid == new Guid("VALUE3")
...
else if (gMyGuid == new Guid("VALUEn")

However by doing this I'm creating a new instance of the Guid each time for a comparison. I could convert the Guid to a string then compare on the string but the string comparison is a pretty long string for comparison.

Any advise is gratefully received.

like image 808
John Mitchell Avatar asked Jun 22 '12 12:06

John Mitchell


People also ask

Can we convert GUID to string C?

ToString(string format) returns a string representation of the value of this Guid instance, according to the provided format specifier. Examples: guidVal. ToString() or guidVal.

Is GUID length fixed?

So the answer is "yes", it will always be the same length.

What does GUID Parse do?

The Parse method trims any leading or trailing white space from input and converts the string representation of a GUID to a Guid value. This method can convert strings in any of the five formats produced by the ToString(String) and ToString(String, IFormatProvider) methods, as shown in the following table.

Is a GUID a string?

A GUID is a 16-byte (128-bit) number, typically represented by a 32-character hexadecimal string.


1 Answers

You can create a System.Collections.Generic.Dictionary<Guid, ...> where ... is something useful to you.

Upon program startup, fill the dictionary with the guids and values that you need to recognize.

Then, use the TryGetValue method of the dictionary to retrieve a value by its guid.

I haven't stated anything literal for ... because I don't know what you want to do with the guids. Maybe you want to run some function, then a method pointer (Func<T> or something like that) might be appropriate, or otherwise an interface type that provides the method you want to invoke. This depends on the context/purpose of that guid comparing code.

like image 178
O. R. Mapper Avatar answered Sep 22 '22 14:09

O. R. Mapper