I am coming from JavaScript and trying to better understand working with object in C#. I have some simple code:
class Program
{
static void Main(string[] args)
{
MyClass firstObj = new MyClass();
firstObj.Number = 6;
Console.WriteLine(firstObj.Number);
object secondObj = doResults();
string getString = secondObj.GetType().GetProperty("resultsString").GetValue(secondObj).ToString();
Console.WriteLine(getString);
Console.ReadLine();
}
public static object doResults()
{
ResultsObj newResults = new ResultsObj();
newResults.resultsString = "Here is my string";
return newResults;
}
}
public class MyClass
{
public int Number { get; set; }
}
public class ResultsObj
{
public string resultsString { get; set; }
}
In the first part of Main(), I create an object, add a property, set a value and then access and display that value. Its all pretty straight forward.
In the second part of Main(), I call the doResults() method, which creates an object a string property.
My questions is this line:
string getString = secondObj.GetType().GetProperty("resultsString").GetValue(secondObj).ToString();
It seems so involved to me. Is that really the proper/most efficient way to access the properties of the returned object?