-2

I want to have a property in my class which can be of two types in .net6.

Class A {
    public string Name {get;set;}
    public int Age {get;set;}
}

Class B {
    public string Name {get;set;}
}

//I want something like below:
Class MyClass{
public <A|B> myProperty {get;set;}
}


myProperty can be of any type A or B from the API response. How to deserialize this into A or B? Can anybody help how to achieve this?

Havyia Ayv
  • 73
  • 2
  • 5

1 Answers1

0

First, you create an interface with the properties common to both A and B:

interface IHasName
{ 
     public string Name { get; set; }
}

Then you have your classes implement that interface:

class A : IHasName
{
    public string Name { get; set; }
    public int Age { get; set; }
} 
// same for class B

and finally you can use the interface type instead of A|B:

class MyClass
{
    public IHasName MyPropertyContainingAOrB { get; set; }
}
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • When I deserialize into the class type MyClass, I cannot access the property Age from MyPropertyContainingAOrB. How to solve this? – Havyia Ayv Jan 10 '23 at 16:01
  • @HavyiaAyv: Well, `A` does not have a property Age. If you are sure that MyPropertyContainingAOrB contains a value of type B, you can cast it: `var age = ((B)myClassInstance.MyPropertyContainingAOrB).Age;`. – Heinzi Jan 10 '23 at 16:49