vendredi 18 septembre 2020

C# Get Objects Attribute, create if null and set reference

I encountered the following problem: Imagine you have an object TypeA objA with objA.objBof TypeB. You want to create a variable TypeB objC = objA.objB, but if objB is null a new object of type TypeBshould be created. This is easy using ??. However the reference in objA will not get updated by that.

I'm unable to come up with a method, such that it takes any object (not only of TypeA), a string for the attribute name (not always of TypeB), and returns the correct type. Obviously one would need generics and reflection, but since the attribute type is derived within the method the generic type can not be inferred when calling the method. Therefore it throws an error.

I'm not allowed to touch the getter and want to avoid writing two lines where instead I want to call the function.





Aucun commentaire:

Enregistrer un commentaire