Skip to content

Commit 44d9f63

Browse files
Small cleanup and bugfix in TryGet (Azure#49448)
Co-authored-by: Daniel Marbach <[email protected]>
1 parent 8e55b99 commit 44d9f63

File tree

2 files changed

+21
-12
lines changed

2 files changed

+21
-12
lines changed

sdk/eventgrid/Azure.Messaging.EventGrid/src/EventGridEvent.cs

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,13 @@ internal EventGridEvent(EventGridEventInternal eventGridEventInternal)
114114
/// <returns> Whether or not the event is a system event.</returns>
115115
public bool TryGetSystemEventData(out object eventData)
116116
{
117+
// the property can be set to null after the creation of the event.
118+
if (Data == null)
119+
{
120+
eventData = null;
121+
return false;
122+
}
123+
117124
try
118125
{
119126
JsonDocument requestDocument = JsonDocument.Parse(Data.ToMemory());
@@ -155,7 +162,7 @@ public static EventGridEvent[] ParseMany(BinaryData json)
155162
egEvents[i++] = new EventGridEvent(EventGridEventInternal.DeserializeEventGridEventInternal(property));
156163
}
157164
}
158-
return egEvents ?? Array.Empty<EventGridEvent>();
165+
return egEvents ?? [];
159166
}
160167

161168
/// <summary>
@@ -171,19 +178,15 @@ public static EventGridEvent Parse(BinaryData json)
171178
{
172179
Argument.AssertNotNull(json, nameof(json));
173180
EventGridEvent[] events = ParseMany(json);
174-
if (events.Length == 0)
175-
{
176-
return null;
177-
}
178-
if (events.Length > 1)
181+
return events.Length switch
179182
{
180-
throw new ArgumentException(
183+
0 => null,
184+
> 1 => throw new ArgumentException(
181185
"The BinaryData instance contains JSON from multiple event grid events. This method " +
182-
"should only be used with BinaryData containing a single event grid event. " +
183-
Environment.NewLine +
184-
$"To parse multiple events, use the {nameof(ParseMany)} overload.");
185-
}
186-
return events[0];
186+
"should only be used with BinaryData containing a single event grid event. " + Environment.NewLine +
187+
$"To parse multiple events, use the {nameof(ParseMany)} overload."),
188+
_ => events[0]
189+
};
187190
}
188191
}
189192
}

sdk/eventgrid/Azure.Messaging.EventGrid/src/EventGridExtensions.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ public static class EventGridExtensions
2525
public static bool TryGetSystemEventData(this CloudEvent cloudEvent, out object eventData)
2626
{
2727
BinaryData data = cloudEvent.Data;
28+
if (data == null)
29+
{
30+
eventData = null;
31+
return false;
32+
}
33+
2834
try
2935
{
3036
JsonDocument requestDocument = JsonDocument.Parse(data.ToMemory());

0 commit comments

Comments
 (0)