I have a constructor that performs initialization on the switch as follows:
class Foo { public readonly int Bar; public readonly object Baz; public Foo(int bar, string baz) { this.Bar = bar; switch (bar) { case 1:
I am still doing this, but as soon as this is done, it will easily be a few hundred lines. I am not a fan of creating such a constructor, but I don’t understand how to safely circumvent this language function (and bypassing in general is what I do not want to do). Maybe there should be a hint that there is something fundamentally wrong with what I'm trying to do, but I'm not sure.
Basically, I want to perform complex initialization in my own immutable type. What is the best way to do this? Is the gazillion string constructor terrible in this case?
Update: Just for the sake of clarification, I want to maintain immutability in a class that would initialize instances in a complex way in the best way. I am writing a class representing a randomly generated token, FormatToken , which is usually a character.
Complex initialization parses the format string (note: I'm not trying to parse a regular expression to generate a random string, I don't want to spend my next 20 lives doing this :)). Initially, I wrote something that would accept input through a constructor parameter, e.g.
+ /// Format tokens + /// c{l} Lowercase Roman character in the ASCII range. + /// v{L} Uppercase Roman character in the ASCII range. + /// c Roman character in the ASCII range. + /// d Decimal. + /// d{0-9} Decimal with optional range, both minimum and maximum inclusive. var rand = new RandomString("c{l}C{L}ddd{0-4}d{5-9}"); rand.Value == /* could equal "fz8318" or "dP8945", but not "f92781".
The class that ultimately raised this question was what each of these tokens represents. The initialization issue is related to the possibility of supporting various formats (ASCII characters, Roman alphabet, decimals, characters, etc.)
This is the actual code in question:
internal class FormatToken { public TokenType Specifier { get; private set; } public object Parameter { get; private set; } public FormatToken(TokenType _specifier, string _parameter) {
I used readonly initially because I misunderstood the reason for using it. Just removing readonly and replacing it with an auto-property (i.e. { get; private set; } will take care of my immutability.
This question has become more about initialization tasks and less about FormatToken . Perhaps “How to do complex, possibly unknown initialization” is now the best question. Now it’s quite obvious to me that having a giant switch is a bad idea. The factory sample is certainly intriguing for what I am doing, and I think it answers the question I have. I just want to give him a couple more days.
Thank you so much for your thoughts! I leave the original code example here to save the answers.