'Create an object with only specified properties depending on previous selection C#

I want to create an object from a class, but with the restriction of the selected enum.

Example:

  1. Is Enum.X selected then the object may have only name.
  2. Is Enum.Y selected then the object may have only age.
  3. Is Enum.Z selected then the object may have name and age.

So far all properties are included for each object of MyObjectClass, but in the long run this leads to confusion.

You can imagine my problem like a form, where further information is requested, depending on the previous selection. With the restriction that my problem is only similar, but should solve almost the same.

public class MyObjectClass
{ 
    public MyEnum Enum { get; set; }
     
    public string Name { get; set; }
      
    public string Age { get; set; }
}

How can something like this be implemented in C#?



Solution 1:[1]

I am not sure what you want to achieve. Normally in c# you would have MyObjectClass implement several interfaces that expose only the intended properties. Thus the code setting the enum could decide what interface to choose.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Clemens