How to write below logic in general way?
I have a model like below
public sealed class Person
{
public string MobileNo { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
In my implmentation class, I have a method that takes IEnumerable
as a parameter
public string PersonList(string listName, IEnumerable<Person> persons)
{
dictionary.Add("name", new String[1] { listname });
dictionary.Add("list", persons.ToArray());
PrivateMethod("personList", dictionary);
}
I have another private method
private string PrivateMethod(string value, Dictionary<string, object[]> parameters)
{
foreach (KeyValuePair<string, object[]> kvp in parameters)
{
Person[] persons = kvp.Value.Cast<Person>().ToArray();
[...]
}
[...]
}
I want to make this above method multiple, and I don't want the Personality model to be tightly coupled.
Can i use dynamic ?
ContactList(string listName, IEnumerable<dynamic> persons)
And within the private method
dynamic[] persons = kvp.Value.Cast<
How to pass the model here >().ToArray();
Decision:
This will work great.
dynamic[] persons = kvp.Value.Cast<dynamic>().ToArray();
Thanks to usr and Rune FS
+3
source to share
2 answers
Have you tried using "Interfaces" in C #? you can use any object for any type as long as they are all derived from the same interface type.
interface IPerson
{
string MobileNo { get; set; }
string Name { get; set; }
string LastName { get; set; }
}
class Person : IPerson
{
public string MobileNo { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
class execute
{
private Dictionary<string, object[]> dictionary = new Dictionary<string,object[]>();
public void run()
{
List<IPerson> persons = new List<IPerson>();
persons.Add(new Person()
{
LastName = "asdf",
Name = "asdf",
MobileNo = "123123"
});
persons.Add(new Person()
{
LastName = "aaaa",
Name = "dddd",
MobileNo = "1231232"
});
string x = PersonList("somelistname", persons);
}
public string PersonList(string listName, IEnumerable<IPerson> persons)
{
//dictionary.Add("name", new String[1] { listName });
dictionary.Add("list", persons.ToArray());
return PrivateMethod("personList", dictionary);
}
private string PrivateMethod(string value, Dictionary<string, object[]> parameters)
{
foreach (KeyValuePair<string, object[]> kvp in parameters)
{
IPerson[] persons = kvp.Value.Cast<IPerson>().ToArray();
}
return "somestring";
}
0
source to share