I’m trying to consume a Web API. I created a class so that I can deserialize the data I get back. The problem is that the returned object has these two properties:
public string id { get; set; }
public string set_id { get; set; }
The set_id
related to "sets". The compiler is throwing an error on the set;
from the id
property, saying that it already contains a definition for set_id
.
CS0102 The type ‘MyClass’ already contains a definition for ‘set_id’
Is there any way to solve this without renaming the property?
2
Answers
I would recommend using JsonPropertyName
For example:
this attribute based on your json library , if you use newtonsoft it would be
JsonProperty
Lets findout why we can’t have a 2 variable with names id and set_id together
For understanding this we are going to see IL generated code by c# compiler
for class with 1 property id generated IL looks like this :
In this code you can see getter and setter method are transformed to some 2 methods named set_id and get_id (set_id = set , get_id = get)
Now we have set_id and get_id reserved so we can’t have other field with name set_id or get_id
The code generated by C# compiler creates setters and getters.
set_id
will be created forid
property you have.I would simply rename your
set_id
tosetId
orIdOfSet
…etc.Generally, for property names in C#, it is not a good idea to have underscores if you want to follow the accepted code style patterns.