tags:

views:

138

answers:

2

I have a Variable class and and 3 subclasses: VariableBool, VariableLong and VariableDouble. Each subclass defines only a value member of the type of the suffix.

Now, I need to transfert objects based on these classes over WCF. I have multiple clients registering their variale to a server. Whenever a value changes on one client, it's updated in all other clients.

My question is: is there a way to do:

someVar.Value = anotherVar.Value;

regardless of the type, wihout having to check for type, e.g.:

VariableBool anotherVarBool = anotherVar as VariableBool;
if (anotherVarBool != null) {
  (someVar as VariableBool).Value = anotherVar.Value;
}
// check other types...

What am I missing? Is there a patern of some kind? Could I use reflection? Also, I don't think I can use Generics because of the WCF (I've tried but I could make it work).

Thanks

+1  A: 

If you are using mex-generated WCF proxies, then I suspect reflection (or ComponentModel) is indeed the simplest option - something like:

public static void Copy<T>(T source, T destination,
    string propertyName) {
    PropertyInfo prop = typeof(T).GetProperty(propertyName);
    prop.SetValue(destination, prop.GetValue(source, null), null);
}

Or if you want to use it even with the variable types as the base-class:

public static void Copy(object source, object destination,
    string propertyName) {
    PropertyInfo sourceProp = source.GetType().GetProperty(propertyName);
    PropertyInfo destProp = destination.GetType().GetProperty(propertyName);
    destProp.SetValue(destination, sourceProp.GetValue(source, null), null);
}
Marc Gravell
Thank you, that's exactly what I was looking for :)
Julien Poulin
+1  A: 

Why don't you to put the Value member in the base class Variable. In that case,

public void UpdateValue( Variable variable )
{
   if( variable != null )
      // do something with variable.Value
}

However, if you really want to use inheritance, you need to tell the base class what are the sub types by using KnownType attribute and its method

[DataContract()]
[KnownType( "GetKnownType" )]
public class Variable
{

 public object Value;

 private static Type[] GetKnownType()
 {
   // properties
   return new []{ typeof(VariableBool),
                  typeof(VariableLong), 
                  typeof(VariableDouble),};
 }
}

[DataContract()]
public class VariableBool : Variable
{
}

[DataContract()]
public class VariableLong : Variable
{
}

[DataContract()]
public class VariableDouble : Variable
{
}
codemeit
Thanks, I'll combine your answer with the solution. The subclasses will only be used to get a typed value
Julien Poulin