Reputation: 32740
I am building a simple custom lightweight csv generator class named, oddly enough, CsvWriter<T>
.
The way this class works is that it will automatically generate a csv to an underlying Stream
from all public properties that are marked with a predefined attribute that we aptly named CsvPropertyAttribute
.
Upon object creation I would like to check that the generic type implements at least one public property with the predefined CsvPropertyAttribute
. If that weren' the case I'd like to throw an exception as the generic type parameter is not really valid.
The questions that arise are the following:
WriteLine(T record)
or similar mehtod (lazy initialization).csv
empty? There is no way I can constraint the generic parameter to valid types.ArgumentException
seems the better fit but its still not quite right.Thank you.
Upvotes: 3
Views: 118
Reputation: 51330
You can even throw an exception from the class constructor (aka static constructor). That way you can do your checks/initializations only once per T
.
If the class constructor fails for CsvWriter<Foo>
, you won't be able to even call the constructor of CsvWriter<Foo>
.
If you're worried about proper argument typing, you could create a custom exception type. It's the cleanest solution. But I wouldn't worry about it that much since if you use the class constructor, your exception will be wrapped in a TypeInitializationException
either way.
Upvotes: 2
Reputation: 3813
This is really something that should be a compile-time error, but the language doesn't support it.
1: Yes, go ahead and throw in the constructor. This fail-fast technique will make it less likely you ship bad code.
2: Throw as soon as possible. Don't create the file.
3: I'd create a subclass of InvalidOperationException
. You may think of something better.
Also, I highly recommend writing a unit test not only for this class, but for any other code that ever instantiates it.
You may also want to re-think your design. Maybe an interface to give you the basics.
Upvotes: 1