Reputation: 69
I have this service that will be call from a Web API and I want to see if there is a way to combine the two together using the model that is being passed in?
Can I use something like getType to see the type of object?
public ResultStatus InsertUsersDownload(UserLog userLog)
{
return Db.UsersDownload(userLog);
}
public ResultStatus InsertNonUsersDownload(NonUserLog nonUserLog)
{
return Db.NonUsersDownload(nonUserLog);
}
Model
Upvotes: 0
Views: 307
Reputation: 8743
You could use the is
operator to check the type. Then your method will look like this:
public ResultStatus InsertDownload(object log)
{
if(log is UserLog userLog)
{
return glDb.UsersDownload(userLog);
}
else if(log is NonUserLog nonUserLog)
{
return glDb.NonUsersDownload(nonUserLog);
}
else
{
throw new ArgumentException("invalid type", nameof(log));
}
}
If UserLog
and NonUserLog
share a common base class, you can also use that instead of object
.
But you should really think whether this improves your code. If you have to check for a type and do different stuff depending of the type, this is often a sign of bad class design.
EDIT: I just saw your code of the model. They have the only difference that your UserLog
class has an additional property IsProfessional
. Maybe you could merge your classes into one by adding an additional property IsUser
:
public class Log
{
public string CustomerId { get; set; }
public string FileName { get; set; }
public string Remote_Addr { get; set; }
public string Local_Addr { get; set; }
public string Http_User_Agent { get; set; }
public string Http_Referer { get; set; }
public bool? IsMobile { get; set; }
public int? DeviceId { get; set; }
public string AppType { get; set; }
public bool? IsProfessional { get; set; }
public bool IsUser { get; set; }
}
Then you could write your function that way:
public ResultStatus InsertDownload(Log log)
{
if(log.IsUser)
{
return glDb.UsersDownload(log);
}
else
{
return glDb.NonUsersDownload(log);
}
}
This has the advantage that you can the method signature is more expressive than a method that takes an object
as a parameter.
Upvotes: 1