tags:

views:

118

answers:

1

I have a class that contains Append-like members for each primitive type, string and INetSerializable:

   public class TypeAppender
   {
         public void Append(int i ) {}
         public void Append(double d) {}
         public void Append(string s){}i){}
         public void Append(INetSerializable ins){}
    }

From a different class, I want to call this method "generically so to speak", by passing Object

say I have something like that:

class SomeClientClass
{
    TypeAppender _appender=new TypeAppender ();  
    Dictionary<string, Object> _cmdTable =new Dictionary<string, Object>();   

    public void Process()
    {   
        foreach(KeyValuePair<string, Object> pair in cmdTable )   
        {
              _appender.Append(pair.Key);

              Object obj = pair.Value;
              if (obj is int)
                 _appender..Append((int)obj);
              else if (obj is double)
                 _appender..Append((double)obj);
              else if (obj is char)
                 _appender..Append((char)obj);
              else if (obj is string)
                 _appender..Append((string)obj); 
        }
    }     
    public void AddParam<T>(string key, T value)
    {
            _cmdTable.Add(key, value);
    }
}

Question #1: Will pair.Value be unboxed to a correct primitive? s

Question #2: Any problesm with AddParam member function?

Thanks

+1  A: 

No.

With the code as is, it will fail to compile as there is no suitable conversion from object -> non-object type. You will have to manually convert the code to the appropriate type.

One option is to provide an overload of Append of type Object and do the logic there.

void Append(object obj) {
  if ( obj is int ) {
    Append((int)obj);
  } else if ( obj is double) { 
    Append((double)obj);
  ...
}

EDIT Question #2

There is nothing wrong in the sense that it will function correctly. However it doesn't seem to add any value to your application over having a non-generic one which takes an object parameter.

JaredPar
This will be painful. Any good workarounds other than you've stated or having different Dictionaries for each supported type?
@Sasha, unfortunately without a late binding mechanism (VB or C# 4.0) this is really you're only option.
JaredPar
Thanks, applied your method :)
Another questions :)