Igor Cova
Igor Cova

Reputation: 3514

C# how to make constructor for class

I have a class Response with generic parameter:

public class Response<T> where T : class {
  public bool Result;
  public T Data;
}

Also, I have a class Instance with simple parameters

public sealed class Instance {
  public long Rank { get; set; }
  public int ID_Member { get; set; }
}

And then I have a class where I use last ones

public sealed class InstanceResponse : Response<IList<Instance>> { }

And I try to add a constructor to last class and don't understand how to do it

I've tried like there, but it's doesn't work, JsonString contains serialized class InstanceResponse

public sealed class InstanceResponse : Response<IList<Instance>> {
  public InstanceResponse(string JsonString) {
    this = JsonConvert.DeserializeObject<InstanceResponse>(JsonString);
  }
}

I've got an error Cannot assign to 'this' because it is read-only

How it possible?

Upvotes: 2

Views: 87

Answers (1)

Fabjan
Fabjan

Reputation: 13676

It's not possible to deserialize json to the object and assign it directly in ctor to the object itself using this keyword.

Provided that

Json contains serialized class InstanceResponse

You can do something like this:

public sealed class InstanceResponse : Response<IList<Instance>> {
  public InstanceResponse(string JsonString) {
    var response = JsonConvert.DeserializeObject<InstanceResponse>(JsonString);
    this.Data = response.Data;
    this.Result = response.Result;
  }
}

Another possible solution is to deserialize json in a code that creates instance of InstanceResponse (call's ctor) somewhere.

Instead of:

var response = new InstanceResponse(json);

You could deserialize json right there:

var response = JsonConvert.DeserializeObject<InstanceResponse>(json);

P.S.

With that being said, an interesting point was raised by @Lasse Vågsæther Karlsen regarding the subject. It is actually possible to assign something to this however it is only working inside of a structs ctor and use cases for it are very limited...(thanks Lasse)

Upvotes: 5

Related Questions