Creating a function with a common return type

I currently have the following function

public int GetVariableValue(TaxReturn taxReturnObj, string identityKey) { int returnTypeOut = 0; if (taxReturnObj.Identity.ContainsKey(identityKey)) { int.TryParse(taxReturnObj.Identity[identityKey], out returnTypeOut); } return returnTypeOut; } 

To get the value, we use the following code,

eg.

 int valPayStatus = GetVariableValue(objTaxretrun, TaxReturnIdentity.aadata_identity_paystatus) 

It has worked fine so far since all Identity values ​​were Integer, but recently we have added new identifiers with the String and Boolean types. So I want to make the Generic function above ... but I don’t know how to do it, I tried to do a google search, but didn't find anything.

+4
source share
4 answers
  public T GetVariableValue<T>(TaxReturn taxReturnObj, string identityKey) { if (taxReturnObj.Identity.ContainsKey(identityKey)) { return (T) Convert.ChangeType(taxReturnObj.Identity[identityKey], typeof(T)); } else { return default(T); } } 
+3
source

I would do this, maybe the best way:

 public T GetVariableValue<T>(TaxReturn taxReturnObj, string identityKey) { if (taxReturnObj.Identity.ContainsKey(identityKey)) { if(typeof(T) == Int32) { int returnTypeOut = 0; int.TryParse(taxReturnObj.Identity[identityKey], out returnTypeOut); return returnTypeOut; } else if (typeof(T) == System.String) { //code here } } return default(T); } 

And you could call it that

 int valPayStatus = GetVariableValue<int>(objTaxretrun, TaxReturnIdentity.aadata_identity_paystatus) string valPayStatusStr = GetVariableValue<string>(objTaxretrun, TaxReturnIdentity.aadata_identity_paystatus) 
+5
source
 public T GetVariableValue<T>(TaxReturn taxReturnObj, string identityKey) { if (taxReturnObj.Identity.ContainsKey(identityKey)) { return (T)taxReturnObj.Identity[identityKey]; } return default(T); } 

Something like that? This does not mean that he will not challenge if you pass him the wrong tho type.

+1
source

You can try something like this:

 public T GetVariableValue<T>(TaxReturn taxReturnObj, string identityKey) { if (taxReturnObj.Identity.ContainsKey(identityKey)) { return taxReturnObj.Identity[identityKey]; } return default(T); } 

if you found key in your Identity dictionary, then return that particular value without parsing it, or you can return the default value

+1
source

All Articles