I have a said class given below:
public class ABC : XYZ
{
public string Username { get; set; }
public string Password { get; set; }
}
I am passing this class into another class as:
public class otherClass : someClass, someInterface
{
private readonly ABC _ABC;
public PythonRunner(ILogger<com> logger, ABC ABC)
: base(logger, acpApiService, apxApiService, logAttributes, mapper)
{
ABC = ABC;
}
Public Void SomeFunc()
{ Console.WriteLine(_ABC.username)
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("username", _ABC.Username);
dic.Add("password", _ABC.Password);
}
}
Is there a way to dynamically do this? What I mean is I don't want to keep stating the dic.Add("password", _ABC.Password);
for each key-value pair I want to enter in the dictionary. There are multiple records and I'd like to loop through them, if there is a way. I am also quite new to C# so please let me know if you need any other information.
CodePudding user response:
I had to make some corrections to run, but you can do it using the code below. I'm using .NET 6 but it will run for previous versions.
foreach(var prop in _ABC.GetType().GetProperties())
{
_dic.Add(prop.Name, _ABC.GetType().GetProperty(prop.Name).GetValue(_ABC, null).ToString());
}
Example:
var user = new UserModel()
{
Username = "Someone",
Password = "SafePassword"
};
var other = new OtherClass(user);
other.PrintDictonary();
public class UserModel
{
public string Username { get; set; }
public string Password { get; set; }
}
public class OtherClass
{
private readonly UserModel _ABC;
private Dictionary<string, string> _dic = new Dictionary<string, string>();
public OtherClass(UserModel ABC)
{
_ABC = ABC;
SomeFunc();
}
public void SomeFunc()
{
foreach(var prop in _ABC.GetType().GetProperties())
{
_dic.Add(prop.Name, _ABC.GetType().GetProperty(prop.Name).GetValue(_ABC, null).ToString());
}
}
public void PrintDictonary()
{
foreach(KeyValuePair<string, string> entry in _dic)
{
Console.WriteLine($"Key: { entry.Key } Value { entry.Value }");
}
}
}
//It will print in console:
//Key: Username Value Someone
//Key: Password Value SafePassword