I've looked over a few similar questions here and browsed a few articles on the web and haven't reached a solid conclusion that makes sense on this question. Everything I've read seems to be related to throwing something like an ArgumentException
or an ArgumentOutOfRangeException
. However, I don't believe that these apply based on what I've read so far. If they truly do apply to my situation can you please explain (and provide documentation) as to why it is the best fit?
I have a generic class Foo<T>
that has a property of type T
. The type T
is only valid if it is one of two types Bar
and BarFoo
. Therefore there is an exception thrown in the constructor if T
is an invalid type:
public class Foo<T> {
public T ID { get; private set; }
public Foo(T id) {
if (typeof(T) != typeof(Bar) || typeof(T) != typeof(BarFoo))
throw new Exception("Invalid type message goes here...");
if (id is Bar)
ID = (Bar)(object)id;
else if (id is BarFoo)
ID = (BarFoo)(object)id;
}
}
This is a simple example, but I'm not sure what exception should be thrown in this case since T
is specified at the time of creating the object:
Foo<int> myFoo = new Foo<int>(3);
What exception should be thrown when the type of T
is supplied at the class level instead of method level? If both are treated the same, then please provide a thorough explanation as to why this is true.
NOTE
Question has been closed, and design has since been changed. I suggest viewing the duplicate, or the answer below. No further comments are necessary.