Friday, July 17, 2015

Set a getsetter by matching its name to a magic string in C#.

This comes from here and seems to work. This test passes:

using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Atty.Core.Tests
{
   [TestClass]
   public class AnotherTest
   {
      [TestMethod]
      public void reflection_works()
      {
         Person person = new Person()
         {
            Name = "Ty Ng",
            UsStateOfResidence = "Iowa",
            Mantra = "It's OK to cry."
         };
         object red = "Red";
         person.GetType().GetProperty("FavoriteColor").SetValue(person, red, null);
         Assert.AreEqual(person.FavoriteColor, "Red");
      }
   }
}

 
 

At .SetValue the first parameter is the instance to affect and the object handed in for the second parameter seems to be the value the getsetter in question, in this case FavoriteColor, is going to get set to. We can hand in almost any type (not dynamic) for the second parameter revealing that an object is expected. Under the hood, the object is upcast to the appropriate type, or at least there is an attempt to do so. In this example, the Person object is the same as the one defined here.

No comments:

Post a Comment