user3768388
user3768388

Reputation: 43

Taking multiple types in a property setter

I want to option 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 that makes sense, I am only ever setting the Property as one type but I would like to be able to assign to it with other types and then transform them within the setter - is this possible?

Upvotes: 4

Views: 10883

Answers (2)

Diligent Key Presser
Diligent Key Presser

Reputation: 4263

What you want looks like design error. In C# property's setter and getter have always the same type. So you have basically next choices:

  • Make your property type object (or dynamic if you want to get even worse design) and transform values within the setter as you stated in the question - i strongly recommend to avoid this approach.
  • Get away from property concept and create separate methods to get value of the field and assign from different types. This approach will allow you to assign value if you dont know the type at compile-time while getter-method will be typed still correctly. But generally it still looks like bad design.
  • Make all the transformations outside the property, This solution is preferred. You should know which type you will use in every separate case.

Upvotes: 7

Basher
Basher

Reputation: 61

Try Property type as object.

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

Upvotes: -1

Related Questions