Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I almost alway regret relying on something like this. Static methods and classes can limit you later on. If you wanted to code some special behavior for your Type class later you would be boxed in. </p> <p>So here is a slight variation on your approach. It is a bit more code but it will allow you to have a custom Type defined later that lets you do custom things.</p> <pre><code> abstract class TypeBase { private static bool _initialized; protected static void Initialize() { if (!_initialized) { Type&lt;int&gt;.Instance = new Type&lt;int&gt; {Name = "int"}; Type&lt;long&gt;.Instance = new Type&lt;long&gt; {Name = "long"}; Type&lt;double&gt;.Instance = new Type&lt;double&gt; {Name = "double"}; _initialized = true; } } } class Type&lt;T&gt; : TypeBase { private static Type&lt;T&gt; _instance; public static Type&lt;T&gt; Instance { get { Initialize(); return _instance; } internal set { _instance = value; } } public string Name { get; internal set; } } </code></pre> <p>Then later when you get to adding a virtual method to Type and want a special implementation for Type you can implement thus:</p> <pre><code>class TypeInt : Type&lt;int&gt; { public override string Foo() { return "Int Fooooo"; } } </code></pre> <p>And then hook it up by changing </p> <pre><code>protected static void Initialize() { if (!_initialized) { Type&lt;int&gt;.Instance = new TypeInt {Name = "int"}; Type&lt;long&gt;.Instance = new Type&lt;long&gt; {Name = "long"}; Type&lt;double&gt;.Instance = new Type&lt;double&gt; {Name = "double"}; _initialized = true; } } </code></pre> <p>My advice would be to avoid static constructors - it is easy to do. Also avoid static classes and where possible static members. I am not saying never, just sparingly. Prefer a singleton of a class to a static. </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