Introducing multiple types into the property setter

I want to set a property with multiple types and am struggling to find a solution.

public static PropertyType Property
        {
            get { return Property;}
            set {
                if (value.GetType() == typeof(PropertyType))
                {
                    Property = value;                       
                }

                //Or any other type
                if (value.GetType() == typeof(string))
                {
                    Property = FunctionThatReturnsPropertyType(value);
                }
            }
        }

      

I hope this makes sense, I am only setting a property as one type, but I would like to be able to assign other types to it and then convert them to a setter - is that possible?

+3


source to share


2 answers


What you want looks like a design error. In C #, the setter and getter are always the same type. So you basically have the following options:



  • Make your property type object

    (or dynamic

    if you want an even worse design) and convert the values ​​to a setter as you stated in the question - I highly recommend avoiding this approach.
  • Step away from the concept property

    and create separate methods to get the field value and assignment from different types. This approach will allow you to assign a value if you don't know the type at compile time, while the getter method will be entered correctly. But overall it still looks like a bad design.
  • Make all transformations outside of the property. This is the preferred solution. You need to know which type you will be using in each case.
+4


source


Try property type as object.



public static Object PropertyName
{
    get { return PropertyName; }
    set { PropertyName = value; }
}

      

0


source







All Articles