Is there a way to enforce/limit the types that are passed to primitives? (bool, int, string, etc.)
Now, I know you can limit the generic typ
If you can tolerate using factory methods (instead of the constructors MyClass you asked for) you could always do something like this:
class MyClass
{
private readonly T _value;
private MyClass(T value) { _value = value; }
public static MyClass FromInt32(int value) { return new MyClass(value); }
public static MyClass FromString(string value) { return new MyClass(value); }
// etc for all the primitive types, or whatever other fixed set of types you are concerned about
}
A problem here is that you would need to type MyClass
, which is annoying. There isn't a very good way around this if you want to maintain the private-ness of the constructor, but here are a couple of workarounds:
MyClass
. Make MyClass
inherit from MyClass
and nest it within MyClass
. Move the static methods to MyClass
. This will all the visibility work out, at the cost of having to access MyClass
as MyClass.MyClass
.MyClass
as given. Make a static class MyClass
which calls the static methods in MyClass
using MyClass
(probably using the appropriate type each time, just for giggles).MyClass
which inherits from MyClass
. (For concreteness, let's say MyClass
.) Because you can call static methods defined in a base class through the name of a derived class, you can now use MyClass.FromString
.This gives you static checking at the expense of more writing.
If you are happy with dynamic checking, I would use some variation on the TypeCode solution above.