Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Function with Generic Return Type

Currently i am having 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 retrieve the value we are using following code,

e.g.

int valPayStatus = GetVariableValue(objTaxretrun, TaxReturnIdentity.aadata_identity_paystatus)

It was working fine untill now as All the Identity Values were Integer,but recently we have added New Identites with String and Boolean types. So i want to make the above function as Generic...but i don't know how to go about that,I tried to search on google but couldn't find anything.

like image 843
Amol Kolekar Avatar asked Dec 26 '22 19:12

Amol Kolekar


2 Answers

I would do this, maybe there's a better 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 like this

int valPayStatus = GetVariableValue<int>(objTaxretrun, TaxReturnIdentity.aadata_identity_paystatus)


string valPayStatusStr = GetVariableValue<string>(objTaxretrun, TaxReturnIdentity.aadata_identity_paystatus)
like image 98
saj Avatar answered Dec 29 '22 07:12

saj


    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);
        }
    } 
like image 39
rene Avatar answered Dec 29 '22 09:12

rene