0

Please consider the following immutable type:

public class/struct AServiceOptions {

    public AServiceOptions (Uri baseAddress, int workersCount, TimeSpan maxIdleTime) {
        BaseAddress = baseAddress;
        WorkersCount = workersCount;
        MaxIdleTime = maxIdleTime;
    }

    public Uri BaseAddress { get; }
    public int WorkersCount { get; }
    public TimeSpan MaxIdleTime { get; }
}

Used in the following manner:

public class AService {

    public AService (AServiceOptions options) {
        Options = options;
        Initialize();
    }

    AServiceOptions Options { get; }

    private void Initialize () {
        InitHttpClient(Options.BaseAddress);
        InitWorkers(Options.WorkersCount);
        InitTimer(Options.MaxIdleTime);
    }

    // Service implementation details
}

Is the AServiceOptions type a good candidate for a Struct? Why / Why not?

Andres A.
  • 1,329
  • 2
  • 21
  • 37

3 Answers3

1

No, because this kind of type instances are suitable for being shared during a call stack, and you know that structs are values so you're not sharing the same object when passing it as argument on methods but you're creating copies, unless you use the ref keyword.

In summary, it should be a class.

See this other Q&A to get further details about when to use structs: When to use struct?

Community
  • 1
  • 1
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
1

This is not a good candidate for a struct, because all your AService objects would be limited to using the same options implementation, without a possibility to inherit for subclass-specific options.

This is not possible with a struct:

public struct AServiceOptions {
}
public struct ADerivedServiceOptions : AServiceOptions { // Not possible
}
public class AService {
    public AService(AServiceOptions opt) ...
}
public class ADerivedService {
    public ADerivedService (ADerivedServiceOptions opt) ...
}

In addition, struct does not "buy" you anything: an immutable class would be just as good, and it would also avoid boxing/unboxing if you need to pass options as an object.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

I've designed and implemented an option system. I think the best way to approach this problem is to have a base class 'Option'. My argument on why it should be a class is because the options of most applications tend to grow with time. ( if you are extending the modules, writing new code etc..)

Christo S. Christov
  • 2,268
  • 3
  • 32
  • 57