C # parameter of general type with conditional statement

I am working with an API in C # with some classes as follows. There are two message classes MessageA and MessageB and a number of field classes FieldA , FieldB , etc. All field classes belong to the Field base class.

The message will contain various fields that can be accessed as

msgA.getField(FieldX field)

(copies the FieldX record (if one exists) from msgA to Field ) and

msgB.set(FieldX field) .

There also

msgA.isSetField(FieldX field)

to ensure that the message contains a field of type FieldX .

I need to write a method to take MessageA and copy some fields into MessageB . I now have a working function, but it has a whole bunch of statements like

 FieldX fieldX = new FieldX(); if(msgA.isSetField(fieldX)) { msgA.getField(fieldX); msgB.set(fieldX); } 

This seems silly to me, so I would like to write a separate method for this. I am new to C # and generic types, so I'm not quite sure if this is the best way to do this. After trying a few things, I wrote

 private void SetMessageB<T>(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); } } } 

But that does not work. Inside the internal conditional operator, the type field_t converted to int . It is clear why this will happen (i.e., these functions cannot accept any type as an argument, so the compiler cannot be sure that it will work every time). But I am wondering if anyone can point out a good way to solve the problem. Feel free to contact me with MSDN articles or tutorials or something else. Thanks for any help.

+4
source share
1 answer

It would be wise to use generics here if your message object methods were also generic:

 class Message { bool isSetField<TField>(TField field) where TField : Field { ... } void getField<TField>(TField field) where TField : Field { ... } void set<TField>(TField field) where TField : Field { ... } } 

Then your method can be really general:

 private void SetMessageB<T>(Message msgA, Message msgB, T field) where T : Field { if (msgA.isSetField(field)) { msgA.getField(field); msgB.set(field); } } 
+3
source

All Articles