title: C# Generic Type Parameter with a Conditional Statement
body: <p>I'm working with an API in C# with some classes as follows. There are two message classes <code>MessageA</code> and <code>MessageB</code> and a number of field classes <code>FieldA</code>, <code>FieldB</code>, etc. The field classes all belong to a base class <code>Field</code>.</p>
  
  <p>A message will contain various fields which can be accessed as</p>
  
  <p><code>msgA.getField(FieldX field)</code></p>
  
  <p>(copies the <code>FieldX</code> entry (if it exists) from <code>msgA</code> to <code>field</code>) and</p>
  
  <p><code>msgB.set(FieldX field)</code>.</p>
  
  <p>There's also</p>
  
  <p><code>msgA.isSetField(FieldX field)</code></p>
  
  <p>to make sure a message contains a field of type <code>FieldX</code>.</p>
  
  <p>I need to write a method to take a <code>MessageA</code> and copy over some of fields to a <code>MessageB</code>. I have a working function now, but it has a whole bunch of statements like</p>
  
  <pre><code>FieldX fieldX = new FieldX();
  if(msgA.isSetField(fieldX))
  {
      msgA.getField(fieldX);
      msgB.set(fieldX);
  }
  </code></pre>
  
  <p>This seems silly to me, so I'd like to write a separate method to do this. I'm new to C# and generic types though, so I'm not quite sure the best way to do it. After trying a number of things, I've written</p>
  
  <pre><code>private void SetMessageB&lt;T&gt;(MessageA msgA, MessageB msgB, Field field) where T : Field
  {
      var field_t = field as T;
      if (field_t != null)
      {
          if (msgA.isSetField(field_t))
          {
              msgA.getField(field_t);
              msgB.set(field_t);
          }
      }
  }
  </code></pre>
  
  <p>But this doesn't work. Within the inner conditional statement, the type of <code>field_t</code> gets converted to <code>int</code>. It sort of makes sense <em>why</em> this would happen (i.e., these functions can't take any type as an argument, so the compiler can't be sure it will work every time). But I'm wondering if someone can point out a good way to solve the problem. Feel free to link me to MSDN articles or tutorials or whatnot. Thanks for any help.</p>