0

Following example does not represent the actual class and issue, it has been adapted for various reasons.

I have a List<EnginePart> populated with objects containing byte KeyID, int Length, byte[] Value. Each object was created sequentially and has its own meaning. The list represents "parts to be replaced" and we want to output that to a sales person in a nice format, so he can tell that to the customer. Each part has its own id, lets say 0x20 - cylinder, 0x40 - oil filter.

Now i'd like to add/display a human readable string to each object in a nice way, without iterating through a foreach and checking

if(enginePart.key =="0x20") Console.WriteLine("Cylinder rotation count is " + enginePart.value).

if(enginePart.key =="0x40") Console.WriteLine("Oil filter only filters " + enginePart.value + " of oil).

Is there any other, nicer way to do it? Creating a new class for each engine part is not a possibility.

So far I've come up with 3 possible solutions;

1) Iterate through the list and have a bunch of ifs and WriteLines

2) Add a string to the object on creation, but in that case we still have if statements

3) Create some enum and use that on object creation

2
  • 5
    Please provide more details on your class and your epxected results. Hard to follow your pseudocode. Anyway the usual approach to provide a "human-readable form of a specific instance" is to overwrite ToString in your class. Commented Apr 4, 2019 at 8:52
  • @HimBromBeere thanks for the tip. I've edited the question, hopefully its clearer Commented Apr 4, 2019 at 9:12

2 Answers 2

3

First I'd suggest you to override the TestClass.ToString() Method, so you won't have to build the string describing the current object in your loop.

See https://learn.microsoft.com/dotnet/api/system.object.tostring?view=netframework-4.7.2

Then maybe the 2nd solution would be quite okay, although we'd need more details on what your goal really is, or have the content of your classes.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer! Overriding ToString is definitely on the list. I've edited the question, I hope its clearer now.
2

Usually when you´re after a "human readable string-representation" you should overwrite ToString:

class EnginePart
{
    byte KeyID { get; set; }
    int Length { get; set; }
    byte[] Value { get; set; }

    public override string ToString()
    {
        return KeyId == "0x40" ? "Oil filter only filters " + value :
               KeyId == "0x20" ? "Cylinder rotation count is " + value :
               ...
    }
}

This way you can rely on the class´ own implementation instead of creating your own in client-code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.