Note that there are some explanatory texts on larger screens.

plurals
  1. POCan an enum return a new instance in C#?
    primarykey
    data
    text
    <p>Greetings everyone!</p> <p>I'll try to make my problem simple: I have an <code>enum</code> to select which <code>ObjType</code> I should use (<code>ObjTypeA</code> and <code>ObjTypeB</code> both inherits from <code>ObjType</code>). So I created a method to extend the given <code>enum</code>, in order to return a new instance according to the selected property in the <code>enum</code>, like follows in the code. I think it works more or less like a factory design pattern. So far so good, but eventually, like in the class <code>MyClass</code>, I may attempt to create <code>n</code> instances of <code>ObjTypeA</code> or <code>ObjTypeB</code>, but I'll have to face the <code>if</code> statement everytime I call the <code>GetObjTypeInstance()</code> method. So:</p> <ul> <li>Can an <code>enum</code> return an instance, something like: <code>public enum EObjType { ObjTypeA = new ObjTypeA(), ObjTypeB = new ObjTypeB() }</code>? Actually, it'd be better to append some <code>GetInstance()</code> method to the <code>ObjTypeA</code> and to the <code>ObjTypeB</code> options in the <code>enum</code>. If there's a way to do this, how can I do it? Doing this I'd avoid those if statements every while step.</li> <li>Is there any other (and better) way to this this (if you understood my problem...)? How?</li> </ul> <p>Thanks in advance!</p> <p>Follow the example code:</p> <pre><code>public static class EObjTypeExt { public static ObjType GetObjTypeInstance(this EObjType ot) { if (ot == EObjType.ObjTypeA) { return new ObjTypeA(); } else if (ot == EObjType.ObjTypeB) { return new ObjTypeB(); } throw new ArgumentOutOfRangeException("unrecognized type!"); } } public enum EObjType { ObjTypeA, ObjTypeB } public class MyClass { ObjType[] obj { get; set; } public MyClass(EObjType otEnum, int n) { this.obj = new ObjType[n]; int i = 0; while (i &lt; n) { this.obj[i] = otEnum.GetObjTypeInstance(); i++; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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