Алексей К.
Алексей К.

Reputation: 87

C#: Switch return value type depending on a value

I need an advice, please. The situation is as follows:

I have a library for operationing with some of hardware. One of the parameters of the machine is Quant (how many products should be in a package). It can be of three types:

*quant type | value type*
 Weight     | double
 Pieces     | Integer
 Without    | null

I can create a struct for storing Quant values, for example:

public struct Quant
{
    public QuantTypes QuantType { get; set; }
    public double QuantWeightValue { get; set; }
    public int QuantPieceValue { get; set; }
    ...
}

But during work process i need to check many times the state and value of quant. And it turns difficult, because I need to get value depending on quantType

if(QuantType == QuantTypes.Piece)
{
     if(QuantWeightValue > 5)
          QuantWeightValue += 2.5;
}
else
{     
     if(QuantPieceValue > 5)
          QuantPieceValue  += 2;
}
SetNewQuantToMachine();

I don`t like it. I can make only one field for quant value of double type. But such way opens a possibility to set quant of piece type with non-integer value. In this case I see two solutions:

  1. Manually round the value during set;

  2. Throw an exception if someone tried to set non-integer piece quant;

Maybe someone wiil give me an advice what is best practice to write such a code. Maybe GenericTypes are suitable in this situation?

Upvotes: 1

Views: 139

Answers (2)

Artyom
Artyom

Reputation: 1095

Sorry if i get it wrong. But i can suggest to change "Quant" to class setup base version with all calculation, then create number of inherited classes with a different variables and then just use something like "quant.GetValue()". Does it make sense?

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

Make separate classes for each subtype of Quant. Provide a method that takes IQuant interface, and dispatches to a type-specific override using dynamic:

interface IQuant {
    QuantTypes QuantType { get; }
}
class QuantWeight {
    public QuantTypes QuantType {
        get { return QuantTypes.Weight; }
    }
    public double QuantWeightValue { get; }
}
class QuantCount {
    public QuantTypes QuantType {
        get { return QuantTypes.Pieces; }
    }
    public int PiecesValue { get; }
}

Your public method will look like this:

public void ProcessQuant(IQuant quant) {
    ProcessQuantImpl((dynamic)quant);
}
private void ProcessQuantImpl(QuantWeight weight) {
    ... // Do the real work here
}
private void ProcessQuantImpl(QuantCount pieces) {
    ... // Do the real work here
}

Upvotes: 3

Related Questions