Reputation: 722
I want to eliminate the type testing in the following code snippet.
Does anyone have any idea how I can do this?
public override T Value { get { // I want to use late binding here so that the following call is made: // bOK = _FolderParmT(ref _value, strFParamVal)); // Let the compiler figure out at runtime which func to call based T's type. // Until I do that I'll have to parse the type. // Be sure to update the constructor if you add a new type T TVal = _value; if (_value is string) { string v = null; bOK = _FolderParmT(ref v, strFParamVal); if (bOK) TVal = ((T)((object)(v))); } else if (_value is System.String[]) { string[] v = null; bOK = _FolderParmT(ref v, strFParamVal); if (bOK) TVal = ((T)((object)(v))); } else if (_value is double) { double v = double.MinValue; bOK = _FolderParmT(ref v, strFParamVal); if (bOK) TVal = ((T)((object)(v))); } else if (_value is int) { int v = int.MinValue; bOK = _FolderParmT(ref v, strFParamVal); if (bOK) TVal = ((T)((object)(v))); } else if (_value is long) { long v = long.MinValue; bOK = _FolderParmT(ref v, strFParamVal); if (bOK) TVal = ((T)((object)(v))); } else if (_value is bool) { bool v = false; bOK = _FolderParmT(ref v, strFParamVal); if (bOK) TVal = ((T)((object)(v))); } if (bOK) { base.SendMessage("\"" + _strFolderParameter + "\" setting: \"" + strFParamVal +"\" was used"); return TVal; }
Upvotes: 0
Views: 429
Reputation: 11598
I just went blind. Is there some case that calling the overloaded private method _FolderParmT doesn't work properly? From this example, I can't tell why the generic class is involved in sniffing out types. Given your question, I would eliminate the type checking with:
public class Test<T>
{
private string _something;
private T _value;
public T Prop
{
get
{
T horridRef = default(T);
return _FolderParmT(ref horridRef, _something) ? horridRef : default(T);
}
set { _value = value; }
}
private bool _FolderParmT(ref T horridRef, string something)
{
return true;
}
}
I do believe we have a bit of a disagreement on what late binding is. The other answers involving reflection do allow for late binding, but until someone can correct me, I don't think your version is late binding at all.
I'd also eliminate that ref parameter and just return the value so that you can Mock/Test easily. _FolderParmT seems like it might be a little to coupled to the types involved also, but I can't quite tell from the code you've posted. I hope this helps.
Upvotes: 0
Reputation: 9955
I usually create a Dictionary<Type, Func<...>>
for these kinds of problems.
Upvotes: 1
Reputation: 36553
You could use the dynamic feature of C# 4.0
((dynamic)this)._FolderParmT(ref _value, strFParamVal));
Upvotes: 0
Reputation: 21111
Have you looked at Activator.CreateInstance and (default)? You wont be able to completely eliminate the creation code, you will still most likely have to handle primitives, but you should be able to simplify many of the other cases.
Upvotes: 1