Reputation: 305
i read some posts about properties vs Method, but I'm not sure, which way is correct for my purpose.
Should I use properties to return the Dictionary with the UserData or should I use a Method, because is a Collection of data and of course exceptions are possible to caused by e.g. missing file
class UsersData
{
public int UserID { get; set; }
public string UserName { get; set; }
public string UserPassWord { get; set; }
}
class Test
{
public Dictionary<int, UsersData> Users
{
get
{
return ReadXMLDict(filename);
}
private set
{ }
}
public string filename { get; set; }
public Test()
{
}
private Dictionary<int, UsersData> ReadXMLDict(string filename)
{
Dictionary<int, UsersData> result;
if (!string.IsNullOrEmpty(filename))
{
var XDoc = XDocument.Load(filename).Element("UsersTable");
result = XDoc
.Descendants("Users")
.ToDictionary(x => int.Parse(x.Element("UserID").Value),
(x => new UsersData
{
UserID = int.Parse(x.Element("UserID").Value),
UserName = x.Element("UserName").Value,
UserPassWord = x.Element("UserPassWord").Value
}));
return result;
}
else
{
return null;
}
}
}
Upvotes: 0
Views: 67
Reputation: 64933
Properties are syntactic sugar. They're compiled into methods and they work the same way as methods (f.e. in your case filename
property is compiled into two methods: get_filename
, set_filename
).
You can catch exceptions, handle them and many other things inside a setter or getter, because they're methods.
BTW, if getting the data and filling the whole dictionary requires input parameters, you should stay with a method as is (no properties!).
In the other hand, if there're many methods that could require a common parameter, maybe it's fine that you define a property to hold that parameter and later use it in some other property or method:
public class A
{
public string Param1 { get; set; }
public string PropertyA
{
get
{
// Uses "Param1"
return ...;
}
}
public void Method1()
{
// Uses "Param1" somewhere...
}
public void Method2()
{
// Uses "Param1" somewhere...
}
public void MethodN()
{
// Uses "Param1" somewhere...
}
}
Upvotes: 1