My class needs property type which can only either be string or int -not sure how to best implement
Working on a project to make a simple IT monitoring system - just for fun.
I have a
Possible solutions I can think of: 1. I could just make
INormalisedDataPoint - this represents the interface for ingested Log/Metric data which has been processed and normalised. It has a property called Messages, where I intend to store a List<IMessageField> - so Messages would include things like CPU%: 95%, dataSource: my-macbook, ipAddress: ..... and so on.
I will be ingesting both logs and metrics (numeric values).Possible solutions I can think of: 1. I could just make
IMessageField have a string Name and string Value , and then convert the string to a numeric type, but I'd like to figure out how to accept either type, as a learning experience.
2. I could have a NumericMessageField (which stores a number) and a StringMessageField which stores a string.7 Replies
Here's my code so far:
What you are describing is what's called a Discriminated Union. Some languages like F# support this, but C# unfortunately does not currently have this.
There is a NuGet package that allows you to emulate this:
https://www.nuget.org/packages/OneOf
OneOf 3.0.271
F# style discriminated unions for C#, using a custom type OneOf<T0, ... Tn> which holds a single value and has a .Match(...) method on it for exhaustive matching. Simple but powerful.
I have not used it however.
I'd probably use an
abstract record MessageField and record StringMessageField(string Value) : MessageField;, assuming you need to serialize/deserialize this
then slap on some [JsonDerivedType] and be happy
You don't have to put them into MessageField, or you can also using static MessageField; at the top of the file.
using static FooCurrentNameSpace.MessageField;
or
Then you can write switch expression and switch statements depending on the case.
I miss the point of INormalisedDataPoint though. But I still included it.Thanks for your help everyone