Reputation:
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
Upvotes: 0
Views: 223
Reputation: 755121
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.
Upvotes: 1