Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I tell the compiler that my generics will definitely allow "|=" or casting to int?
    primarykey
    data
    text
    <p>I'm bone new to generics in C#, and I'm attempting to create a method that will use generics. I tripped across the where keyword when attempting to create a local variable, so I'm sure that it will be part of the solution.</p> <p>The reason for this is I have several different enum variables but the method would do the same to each (given a string that is one of the enum's defined values, toggle it on, using the enum like a bit field).</p> <p>I have most of this together, the part I'm now stuck at is being able to tell the generic method it's ok to allow "|=" as I'm certain any type passed in will support the operator.</p> <p>I would like to be able to maintain generality, if possible, so could either be an enum or a List and I would execute different code paths depending on the type.</p> <p>Example of what I'm taking about</p> <pre><code>enum someType { value1 = 1&lt;&lt;0, value2 = 1&lt;&lt;1, value3 = 1&lt;&lt;2 }; // and so on // some more enums private T someMethod&lt;T&gt;(string myIdentifyers) where T: new() { // suppose myIdentifiers is 1 more more of the valid enum options // assume that the correct strings and enum combinations will be passed T retval = new T(); while () { // assume a loop with a method call that parses off one identifyer at a time // if I have to convert the enum to an int first, so be it, but // at this point I can't tell it that a cast to int exists retval |= (T)System.Enum.Parse( typeof(T), oneIdentifyer, false ); } return retval; } </code></pre>
    singulars
    1. This table or related slice is empty.
    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