Should I make an exception if you are using an invalid generic type, and if so, which one?

I am creating a simple custom class generator the csv, called, oddly enough, CsvWriter<T>

.

The way this class works is that it automatically generates a csv to base Stream

from all public properties that are tagged with a predefined attribute that we aptly named CsvPropertyAttribute

.

When creating an object, I would like to check that the generic type implements at least one public property with a predefined one CsvPropertyAttribute

. If this was "a case I would like to rule out, since the type parameter is indeed invalid.

The following questions arise:

  • Can an exception be thrown in the constructor? If it wasn't easy, I could defer looking for valid properties until the first call WriteLine(T record)

    or similar mehtod (lazy initialization).
  • Can an exception thrown by a generic parameter be thrown? Or is it just better to leave the generated csv

    blank? I am unable to restrict the generic parameter to the allowed types.
  • And finally, if the answer to question # 2 is yes, which exception should I use? ArgumentException

    seems better, but its still not quite right.

Thank.

+3


source to share


2 answers


You can even throw an exception from the class constructor (aka static constructor ). This way you can only do your checks / initializations once at a time T

.

If the constructor of the class doesn't work for CsvWriter<Foo>

, you won't even be able to call the constructor CsvWriter<Foo>

.



If you are worried about the correct set of arguments, you can create a custom exception type. This is the cleanest solution. But I wouldn't bother with that, because if you use the constructor of the class, your exception will get wrapped TypeInitializationException

anyway.

+2


source


This is indeed what should be a compile-time error, but the language doesn't support it.

1: Yes, go ahead and run the constructor. This unfortunate technique will make it less likely that you submit bad code.

2: Quit ASAP. Don't create a file.



3: I would create a subclass InvalidOperationException

. You can think of something better.

Also, I highly recommend writing a unit test not only for this class, but any other code that has ever created it.

You can also think about your design. Maybe an interface to give you the basics.

+1


source







All Articles