I have a question about how i can make a common method of the following method's and how can i call the common method. I want to make a generic method which i can use.
private async Task<bool> GetObjA()
{
var ObjA = await _unitOfWork.RepositoryA.CheckExists(TableField, TableFieldValue);
if (ObjA != null)
{
ValidatedObjects.Add(TableName.ToLower(), ObjA);
return true;
}
return false;
}
private async Task<bool> GetObjB()
{
var ObjB = await _unitOfWork.RepositoryB.CheckExists(TableField, TableFieldValue);
if (ObjB != null)
{
ValidatedObjects.Add(TableName.ToLower(), ObjB);
return true;
}
return false;
}
private async Task<bool> GetObjC()
{
var ObjC = await _unitOfWork.RepositoryC.CheckExists(TableField, TableFieldValue);
if (ObjC != null)
{
ValidatedObjects.Add(TableName.ToLower(), ObjC);
return true;
}
return false;
}
CodePudding user response:
You can implement this by making a single generic method that receives the object as a parameter.
This snippet should do the job:
private async Task<bool> GetObj<T>(T myObject)
{
if (myObject != null)
{
ValidatedObjects.Add(TableName.ToLower(), myObject);
return true;
}
return false;
}
Explanation:
Rather than getting the object inside the method, you will pass it as a generic data type to the method. This means you will use unitOfWork outside the method so you can be generic and avoid repeating yourself each time.
References: