Skip to content

Commit 4bf8ed4

Browse files
authored
refactor Resource::SanitizeValue method to be more readable (#2761)
1 parent 66ad39d commit 4bf8ed4

File tree

1 file changed

+19
-47
lines changed

1 file changed

+19
-47
lines changed

src/OpenTelemetry/Resources/Resource.cs

Lines changed: 19 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
using System;
1818
using System.Collections.Generic;
19+
using System.Globalization;
1920
using System.Linq;
2021
using OpenTelemetry.Internal;
2122

@@ -102,61 +103,32 @@ private static KeyValuePair<string, object> SanitizeAttribute(KeyValuePair<strin
102103
sanitizedKey = attribute.Key;
103104
}
104105

105-
object sanitizedValue = SanitizeValue(attribute.Value, sanitizedKey);
106+
var sanitizedValue = SanitizeValue(attribute.Value, sanitizedKey);
106107
return new KeyValuePair<string, object>(sanitizedKey, sanitizedValue);
107108
}
108109

109110
private static object SanitizeValue(object value, string keyName)
110111
{
111112
Guard.Null(keyName, nameof(keyName));
112113

113-
if (value is string || value is bool || value is double || value is long)
114+
return value switch
114115
{
115-
return value;
116-
}
117-
118-
if (value is string[] || value is bool[] || value is double[] || value is long[])
119-
{
120-
return value;
121-
}
122-
123-
if (value is int || value is short)
124-
{
125-
return Convert.ToInt64(value);
126-
}
127-
128-
if (value is float)
129-
{
130-
return Convert.ToDouble(value, System.Globalization.CultureInfo.InvariantCulture);
131-
}
132-
133-
if (value is int[] || value is short[])
134-
{
135-
long[] convertedArr = new long[((Array)value).Length];
136-
int i = 0;
137-
foreach (var val in (Array)value)
138-
{
139-
convertedArr[i] = Convert.ToInt64(val);
140-
i++;
141-
}
142-
143-
return convertedArr;
144-
}
145-
146-
if (value is float[])
147-
{
148-
double[] convertedArr = new double[((float[])value).Length];
149-
int i = 0;
150-
foreach (float val in (float[])value)
151-
{
152-
convertedArr[i] = Convert.ToDouble(val, System.Globalization.CultureInfo.InvariantCulture);
153-
i++;
154-
}
155-
156-
return convertedArr;
157-
}
158-
159-
throw new ArgumentException("Attribute value type is not an accepted primitive", keyName);
116+
string => value,
117+
bool => value,
118+
double => value,
119+
long => value,
120+
string[] => value,
121+
bool[] => value,
122+
double[] => value,
123+
long[] => value,
124+
int => Convert.ToInt64(value),
125+
short => Convert.ToInt64(value),
126+
float => Convert.ToDouble(value, CultureInfo.InvariantCulture),
127+
int[] v => Array.ConvertAll(v, Convert.ToInt64),
128+
short[] v => Array.ConvertAll(v, Convert.ToInt64),
129+
float[] v => Array.ConvertAll(v, f => Convert.ToDouble(f, CultureInfo.InvariantCulture)),
130+
_ => throw new ArgumentException("Attribute value type is not an accepted primitive", keyName),
131+
};
160132
}
161133
}
162134
}

0 commit comments

Comments
 (0)