0

Imagine I have this class

public MyClass
{
    public string FullName { get; set; }
}

I have an api client that returns me this object like this with an extra property called Capitalized which capitalized all string properties for exemple.

public MyResult : MyClass
{
    public MyClass Capitalized { get; set; }
}

Then I can access things like this :

MyResult result = /* call to api with my class */
Console.WriteLine(result.FullName);
Console.WriteLine(result.Capitalized.FullName);

Is there a way to define a generic MyResult like this, because T can be MyClass, YourClass and the response will always be like :

public MyResult<T> : T
{
    public T Capitalized { get; set; }
}

EDIT : thanks to @Maruf reply Eric Lippert explains it here why it is impossible : https://stackoverflow.com/a/5890813/1026105

JuChom
  • 5,717
  • 5
  • 45
  • 78
  • 1
    probably helps: https://stackoverflow.com/a/5890813/17612995 – Maruf Sep 01 '22 at 10:32
  • Doesn't each `MyClass`, `YourClass` etcetera already have to declare its own properties, regardless of how the API is filling it? Why wouldn't it then also include the `Capitalized` property? Abstracting over the fact that each of the classes has a `Capitalized` would be possible with an interface (`interface ICapitalizable { T Capitalized { get; set; } }`), it's just not particularly useful since you can't use `Capitalized` meaningfully without knowing the type. – Jeroen Mostert Sep 01 '22 at 10:34
  • Ultimately it reads like you're better off changing the way the API result is deserialized: return what's in `Capitalized` instead as the base type, and let go of storing both un-capitalized and capitalized data in the same instance (or create a new wrapper type for that, e.g. `record Result(T Uncapitalized, T Capitalized)`). – Jeroen Mostert Sep 01 '22 at 10:41

1 Answers1

0

How about that:

public class MyResult<T> : MyClass where T : MyClass
{
    public T Capitalized { get; set; }
}
Maruf
  • 354
  • 3
  • 8
  • 1
    This would not allow you to access the un-capitalized properties of `T = YourClass`. `MyClass` would necessarily need to be a pretty generic base. – Jeroen Mostert Sep 01 '22 at 10:42