Reputation: 7067
I have a user details class
public partial class UserDetails
{
public int? Level { get; set; }
public string Unit { get; set; }
public string Bio { get; set; }
public bool? Gender { get; set; }
public int? Mobile { get; set; }
public string Photo { get; set; }
}
I am writing an update method:
public bool UpdateDetails(string userId, UserProperties updateProperty, string value)
{
switch(updateProperty)
{
case UserProperties.Unit:
details.Unit = value;
break;
case UserProperties.Photo:
details.Photo = value;
break;
default:
throw new Exception("Unknown User Detail property");
}
May I do something like dynamic property in JavaScript? e.g.
var details = new UserDetails();
details["Unit"] = value;
Update
As of year 2019! How about try to use this new feature?! DynamicObject DynamicObject.TrySetMember(SetMemberBinder, Object) Method
I am trying to figure out how to write it.
Upvotes: 2
Views: 3832
Reputation: 565
If you don't want to use reflection you can slightly tweak Alens solution to use dictionary to store data.
public class UserDetails
{
private Dictionary<string, object> Items { get; } = new Dictionary<string, object>();
public object this[string propertyName]
{
get => Items.TryGetValue(propertyName, out object obj) ? obj : null;
set => Items[propertyName] = value;
}
public int? Level
{
get => (int?)this["Level"];
set => this["Level"] = value;
}
}
Upvotes: 3
Reputation: 1192
The closest thing would be the ExpandoObject:
https://learn.microsoft.com/en-us/dotnet/api/system.dynamic.expandoobject?view=netframework-4.8
For example:
dynamic sampleObject = new ExpandoObject();
sampleObject.test = "Dynamic Property";
Console.WriteLine(sampleObject.test);
Upvotes: 0
Reputation: 1418
You can do it via reflection for properties that exist on the object.
C# has a feature called Indexers. You could extend your code like this to allow for the behavior you are expecting.
public partial class UserDetails
{
public int? Level { get; set; }
public string Unit { get; set; }
public string Bio { get; set; }
public bool? Gender { get; set; }
public int? Mobile { get; set; }
public string Photo { get; set; }
// Define the indexer to allow client code to use [] notation.
public object this[string propertyName]
{
get {
PropertyInfo prop = this.GetType().GetProperty(propertyName);
return prop.GetValue(this);
}
set {
PropertyInfo prop = this.GetType().GetProperty(propertyName);
prop.SetValue(this, value);
}
}
}
Other than that, if you don't know the properties at runtime, you can use the dynamic type.
Upvotes: 5