0

I am working with third party services, my requests are working fine, but I need to pass this result to my model so that I can separate it into an array and be able to set properties based on index as they don't have a key. I am passing this value through an abstract class and inheriting it in my model but when trying to call the property in my model constructor it always returns null even though in my abstract class it has been set.

I have already tried making my property abstract and overriding but it doesn't work. I also tried to pass the values through the constructors but being a T instance and it doesn't allow me, maybe I am doing something wrong.

The question is, in what way can I get the value set?

This is my HttpBase.cs

    public class HttpBase
    {
        public TResponse Post<TResponse>(string url, Dictionary<string, string> body)
            where TResponse : ClassA, new()
        {
            string result = Post(url, body).Result.ToString();
            TResponse response = new TResponse
            {
                JSON = result // this is where I try to set my property
            };

            return response;
        }     
   
        public async Task<string> Post(string url, Dictionary<string, string> body)
        {
           // returns a string separated by '|'. Ex: "abc|abcd|abcde"
        }
    }

ClassA.cs

public abstract class ClassA
    {
        public string JSON { get; set; }
    }

MyModel.cs

    public class MyModel : ClassA
    {
        public MyObject()
        {
            string json = this.JSON; // null
            string[] arr = json.Split('|', '\n').ToArray(); // throws NullReferenceException
        }

        [Position(1)] //Custom Attribute
        public string Name{ get; set; }
    }
Cleptus
  • 3,446
  • 4
  • 28
  • 34
rottter
  • 13
  • 7

1 Answers1

2

The quick answer is because you are trying to use the JSON property too early.

The constructor is being executed before the initializer block, which means you didn't YET assign the value.

Irwene
  • 2,807
  • 23
  • 48
  • Can you explain a little more? Or maybe post a link to some doc – rottter Jan 29 '21 at 09:06
  • https://www.tutorialsteacher.com/csharp/csharp-object-initializer#:~:text=C%23%203.0%20(.,object%20without%20invoking%20a%20constructor. – Chetan Jan 29 '21 at 10:12
  • @rottter I think this question and it's answers on stackoverflow should complete mine : https://stackoverflow.com/questions/2021373/c-sharp-base-constructor-order/2021414 and the initializer syntax you used `new TResponse { JSON = result }`is executed after any and all constructors – Irwene Jan 29 '21 at 21:29