0

I need to create a generic set accesor where i can pass the classname.classname.property and the value to be set. I saw this question and has been answered but i can't implement it on my project.

link is Is it possible to pass in a property name as a string and assign a value to it?

In the sample code below, how can SetValue set a value for length and width?

public interface MPropertySettable { }
public static class PropertySettable {
  public static void SetValue<T>(this MPropertySettable self, string name, T value) {
    self.GetType().GetProperty(name).SetValue(self, value, null);
  }
}
public class Foo : MPropertySettable {
  public Taste Bar { get; set; }
  public int Baz { get; set; }
}

public class Taste : BarSize {
    public bool sweet {get; set;}
    public bool sour {get; set;}
}

public class BarSize {
    public int length { get; set;}
    public int width { get; set;}
}

class Program {
  static void Main() {
    var foo = new Foo();
    foo.SetValue("Bar", "And the answer is");
    foo.SetValue("Baz", 42);
    Console.WriteLine("{0} {1}", foo.Bar, foo.Baz);
  }
}
Community
  • 1
  • 1
queque
  • 1
  • 2

1 Answers1

0

You are trying to set a string value to a Taste object. It works fine using a new instance of Taste

class Program {
   static void Main() {
       var foo = new Foo();
       foo.SetValue("Bar", new Taste());
       foo.SetValue("Baz", 42);
       Console.WriteLine("{0} {1}", foo.Bar, foo.Baz);
   }
}

It will work if BarSize would derive from MPropertySettable.

public interface MPropertySettable { }
public static class PropertySettable
{
    public static void SetValue<T>(this MPropertySettable self, string name, T value) {
        self.GetType().GetProperty(name).SetValue(self, value, null);
    }
}
public class Foo : MPropertySettable
{
    public Taste Bar { get; set; }
    public int Baz { get; set; }
}

public class Taste : BarSize
{
    public bool sweet { get; set; }
    public bool sour { get; set; }
}

public class BarSize : MPropertySettable
{
    public int length { get; set; }
    public int width { get; set; }
}

class Program
{
    static void Main() {
        var barSize = new BarSize();
        barSize.SetValue("length", 100);
        barSize.SetValue("width", 42);
        Console.WriteLine("{0} {1}", barSize.length, barSize.width);
    }
}
Sagi
  • 8,972
  • 3
  • 33
  • 41