Persistant DefaultValueAttributes
-
Hi, Let's have a dream. I have a class with some properties, here a sample :
public class TestClass { private int myint; private string mystring = ""; public TestClass() { } [DefaultValue(100)] public int IntProp { get { return myint; } set { myint = value; } } [DefaultValue("idea")] public string StringProp { get { return mystring ; } set { mystring = value; } } }
I wonder if it is possible to set at runtime the DefaultValue for every properties. My wish is to be able to serialize theses values. So at next startup, the new defaultvalues will be used. So what are the issues ? - It's straightforward to enumerate the current DefaultValueAttribute of every properties. - I think I have to use the ICustomTypeDescriptor to get a dynamic defaultValue attribute. - I really don't know where to put the serialization and deserialization code for putting and getting back the default values. Constructor ? Desctructor ? - Another point, by setting the DefaultValueAttribute of one propertie, will it be set for every instance of the class ? Thanks for helping me. --- Alexandre Jenny -
Hi, Let's have a dream. I have a class with some properties, here a sample :
public class TestClass { private int myint; private string mystring = ""; public TestClass() { } [DefaultValue(100)] public int IntProp { get { return myint; } set { myint = value; } } [DefaultValue("idea")] public string StringProp { get { return mystring ; } set { mystring = value; } } }
I wonder if it is possible to set at runtime the DefaultValue for every properties. My wish is to be able to serialize theses values. So at next startup, the new defaultvalues will be used. So what are the issues ? - It's straightforward to enumerate the current DefaultValueAttribute of every properties. - I think I have to use the ICustomTypeDescriptor to get a dynamic defaultValue attribute. - I really don't know where to put the serialization and deserialization code for putting and getting back the default values. Constructor ? Desctructor ? - Another point, by setting the DefaultValueAttribute of one propertie, will it be set for every instance of the class ? Thanks for helping me. --- Alexandre JennyImplement the
ICustomTypeDescriptor
in your class. In the implementation forGetProperties
you can attach all the attributes to your PropertyDescriptors that you want. I use this for an object with "properties" that are allocated from a database, and I add aDefaultValueAttribute
to thosePropertyDescriptor
s from the database as well. If you simply want to serialize these, then you use theTypeDescriptor.GetProperties
method to get thePropertyDescriptorCollection
and enumerate those properties, getting the value from theDefaultValueAttribute
which may be found inPropertyDescriptor.Attributes
(inheritted fromMemberDescriptor
).Microsoft MVP, Visual C# My Articles