Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Windows Forms designer from generating default value assignments for properties?

Tags:

c#

.net

winforms

I have a user control with a property that is of a reference type. The Windows Forms designer keeps generating code that assigns the property's initial value to null. How can I prevent this?

I tried adding Reset and ShouldSerialize methods -- Reset had an empty body and ShouldSerialize always returned false -- but that did not work. I also applied the BrowsableAttribute and set it to false.

Edit:

The property's type is a class in the same project. It's not a component or control, just a plain class inheriting from Object. Also, the property's setter calls a method using the property's value as its argument and the method does not accept null as a valid argument.

Example:

public MyClass Property1 
{
   get { return _property1; }
   set
   {
        _property1 = value;
        SomeMethod(value); // This method throws ArgumentNullException;
   }
}

Note: I do realize that get and set methods would probably be more appropriate here.

like image 982
YWE Avatar asked Jun 02 '10 20:06

YWE


1 Answers

Murky, I could use a snippet. Tell the designer that it shouldn't ever serialize the value of the property:

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public Image Aardvark { get; set; }
like image 104
Hans Passant Avatar answered Nov 09 '22 02:11

Hans Passant