Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you can tolerate using factory methods (instead of the constructors MyClass you asked for) you could always do something like this:</p> <pre><code>class MyClass&lt;T&gt; { private readonly T _value; private MyClass(T value) { _value = value; } public static MyClass&lt;int&gt; FromInt32(int value) { return new MyClass&lt;int&gt;(value); } public static MyClass&lt;string&gt; FromString(string value) { return new MyClass&lt;string&gt;(value); } // etc for all the primitive types, or whatever other fixed set of types you are concerned about } </code></pre> <p>A problem here is that you would need to type <code>MyClass&lt;AnyTypeItDoesntMatter&gt;.FromInt32</code>, 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:</p> <ul> <li>Create an abstract class <code>MyClass</code>. Make <code>MyClass&lt;T&gt;</code> inherit from <code>MyClass</code> <strong>and nest it within <code>MyClass</code></strong>. Move the static methods to <code>MyClass</code>. This will all the visibility work out, at the cost of having to access <code>MyClass&lt;T&gt;</code> as <code>MyClass.MyClass&lt;T&gt;</code>.</li> <li>Use <code>MyClass&lt;T&gt;</code> as given. Make a static class <code>MyClass</code> which calls the static methods in <code>MyClass&lt;T&gt;</code> using <code>MyClass&lt;AnyTypeItDoesntMatter&gt;</code> (probably using the appropriate type each time, just for giggles).</li> <li>(Easier, but certainly weird) Make an abstract type <code>MyClass</code> <strong>which inherits from <code>MyClass&lt;AnyTypeItDoesntMatter&gt;</code></strong>. (For concreteness, let's say <code>MyClass&lt;int&gt;</code>.) Because you can call static methods defined in a base class through the name of a derived class, you can now use <code>MyClass.FromString</code>.</li> </ul> <p>This gives you static checking at the expense of more writing.</p> <p>If you are happy with dynamic checking, I would use some variation on the TypeCode solution above.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload