I have a program in .Net 5 C# that make a HTTP Request and the content (JSON) is deserialized (JsonNewtonsoft) in specific type:
// Class definition
public class FooSerializerModel {
[JsonProperty("latitude")]
public string Latitude { get; set; }
[JsonProperty("longitude")]
public string Longitude { get; set; }
}
// Deserialization
var fooJson = JsonConvert.DeserializeObject<FooSerializerModel>(response);
It works fine, now, I need cast the fooJson
variable type to other type for pass it to Data Layer Method:
public class DataModel {
public string Latitude { get; set; }
public string Longitude { get; set; }
}
I need something like this:
var data = fromJson as DataModel;
But I get this error: Cannot convert type FooSerializerModel
to DataModel
Why?
I know is possible solve this problem using:
var data = new DataModel() {
Latitude = fromJson.Latitude,
Longitude = fromJson.Longitude
}
But if my class has 50 attributes I would have to assign one by one, it would be more lines of code and I could forget some of them when doing it explicitly.
Is it possible to do an implicit assignment on a single line? I have tried this:
var data = fromJson as DataModel; // Error
var data = (DataModel) fromJson; // Error
var data = (DataModel) (object) fromJson; // Exception 'Unable to cast object of type' when use 'dotnet run'
I remember that it is possible to do this in TypeScript if you work with types with interfaces and is easy!