-1

I want to create a new object, and during object creation make an RPC call to get properties for it, and then return the object populated with the properties. See this example:

using Newtonsoft.Json;

class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person(int Id)
    {
        // here would be an RPC call to get the FirstName,LastName. result is JSON
        string result = "{\"Id\": 1, \"FirstName\": \"Bob\", \"LastName\": \"Jones\"}";
        this = JsonConvert.DeserializeObject<Person>(result);

    }
}
class Program
{
    static void Main(string[] args)
    {
        var p = new Person(1);
        // p.FirstName should be Bob
    }
}

I don't know how to do this in the constructor without getting a StackOverflow Exception.

Mark Allison
  • 6,838
  • 33
  • 102
  • 151
  • You are getting StackOverflow exception because DeserializeObject creates a new object, i.e. it calls the constructor. And your constructor calls DeserializeObject, i.e. you created an nedless loop. – Al Kepp Jan 06 '19 at 12:20
  • `var p = Person.StaticFactoryMethod(1);` - although a Model or DTO should not implement its own persistence. – H H Jan 06 '19 at 12:22

1 Answers1

0

One option to consider is to use a static method inside Person:

public static Person GetPerson(int Id)
{
    // here would be an RPC call to get the FirstName,LastName. result is JSON
    string result = "{\"Id\": 1, \"FirstName\": \"Bob\", \"LastName\": \"Jones\"}";
    return JsonConvert.DeserializeObject<Person>(result);

}

This avoids the recursive nature of your original code.

Another option is to change the class to a struct. structs allow you to assign to this (unlike classes). And they have a default constructor (separate to your one taking a parameter) so that there is no recursive behaviour.

mjwills
  • 23,389
  • 6
  • 40
  • 63