Click here to Skip to main content
15,896,557 members
Home / Discussions / C#
   

C#

 
GeneralRe: XML to Excel parsing Pin
Not Active23-Aug-11 9:53
mentorNot Active23-Aug-11 9:53 
GeneralRe: XML to Excel parsing Pin
yoni.kess24-Aug-11 21:06
yoni.kess24-Aug-11 21:06 
QuestionPass object from an app to another Pin
mehrdadc4820-Aug-11 23:50
mehrdadc4820-Aug-11 23:50 
AnswerRe: Pass object from an app to another PinPopular
#realJSOP21-Aug-11 2:56
professional#realJSOP21-Aug-11 2:56 
AnswerRe: Pass object from an app to another [modified] Pin
Manfred Rudolf Bihy21-Aug-11 3:32
professionalManfred Rudolf Bihy21-Aug-11 3:32 
GeneralRe: Pass object from an app to another Pin
Keith Barrow21-Aug-11 9:23
professionalKeith Barrow21-Aug-11 9:23 
GeneralRe: Pass object from an app to another Pin
Manfred Rudolf Bihy21-Aug-11 20:50
professionalManfred Rudolf Bihy21-Aug-11 20:50 
SuggestionTIP: Autosetting properties in C# using DefaultValue attributes Pin
Itai Basel20-Aug-11 14:53
Itai Basel20-Aug-11 14:53 
Don't have the attention span to post as article - but thought this might be interesting:

Automatic properties are great but the annoyance of not being able to set them automatically defers a lot of people from using them.
What we (read - I) want to be able to do something like this:
C#
double MyPie { get; set; } = "3.141";
string MyLove { get; set; } = "Pizza";


The default value attribute in System.ComponentModel is of no help there, though a lot of us (read - me) tried that in the beginning:
C#
[DefaultValue(0.3141)]
double MyPie { get; set; }

[DefaultValue("Pizza")]
string MyLove { get; set; }


Initializing the properties one by one in the constructor is at least as annoying as simply doing this:
C#
double _myPie = 0.3141;
double MyPie { get { return _myPie; } set { _myPie = value; } }

double _myLove = "Pizza";
double MyLove { get { return _myLove; } set { _myLove = value; } }


Luckily the nice little feature of extension methods allows us something not exactly optimal or fully elegant - but functional and a good exercise in C# clockwork.
So with just a bit of hammering we can enable automatic reset properties to their declared System.ComponentModel.DefaultValueAttribute if any was specified.
Test code:
C#
using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;

using CSharpUtils;
namespace MyAppNamespace
{
  public class TestClass
  {
    [DefaultValue(0.3141)]
    public double MyPie { get; set; }

    [DefaultValue("Pizza")]
    public string MyLove { get; set; }

    public TestClass()
    {
      MessageBox.Show(string.Format("MyPie = {0}, MyLove = {1}", MyPie, MyLove == null ? "null" : MyLove));
      int ret = (this as Object).ResetPropsUsingDefaultAttributes(false);
      MessageBox.Show(string.Format("MyPie = {0}, MyLove = {1}. {2} properties we set", MyPie, MyLove == null ? "null" : MyLove, ret));
      MyLove = "My dear wife";
      MessageBox.Show(string.Format("MyPie = {0}, MyLove = {1}", MyPie, MyLove == null ? "null" : MyLove));
      ret = (this as Object).ResetPropsUsingDefaultAttributes(false);
      MessageBox.Show(string.Format("MyPie = {0}, MyLove = {1}. {2} properties we set", MyPie, MyLove == null ? "null" : MyLove, ret));
    }
  }
}


This (as you may have already guessed) is done using an extension method to the System.
You will need a public static class to define the extension method in. here's the basic implementation source (feel free to use the code and extend it's functionality):
C#
using System;
using System.Text;
using System.Reflection;
using System.ComponentModel;

namespace CSharpUtils
{
  static class CSharpUtilsExtensionMethods
  {
    public static int ResetPropsUsingDefaultAttributes(this Object oThis, bool initInheritedProperties)
    {
      int count = 0;
      //BindingFlags.Static
      Type oType = oThis.GetType();
      PropertyInfo[] infos = oType.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
      foreach (PropertyInfo inf in infos)
      {
        if (initInheritedProperties || inf.DeclaringType.Equals(oType))
        {
          object[] oDefAtts = inf.GetCustomAttributes(typeof(DefaultValueAttribute), initInheritedProperties);
          if (oDefAtts.Length > 0)
          {
            DefaultValueAttribute defAtt = oDefAtts[oDefAtts.Length - 1] as DefaultValueAttribute;
            if (defAtt != null && defAtt.Value != null && !defAtt.Value.Equals(inf.GetValue(oThis, BindingFlags.GetProperty, null, null, null)))
            {
              inf.SetValue(oThis, defAtt.Value, BindingFlags.SetProperty, null, null, null);
              count++;
            }
          }
        }
      }
      return count;
    }
  }
}


All that's left now is use out test class (here again - with no message box and other nonsense

C#
using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;

using CSharpUtils;
namespace MyAppNamespace
{
  public class TestClass
  {
    [DefaultValue(0.3141)]
    public double MyPie { get; set; }

    [DefaultValue("Pizza")]
    public string MyLove { get; set; }


    public void ResetProps()
    {
      (this as Object).ResetPropsUsingDefaultAttributes(false);
    }
    public TestClass()
    {
      ResetProps();
    }
  }
}


Notes:
- To use the extension method - the .cs file making the call must have a 'using' declaration of namespace where the extension method resides in.
- Passing true for parameter initInheritedProperties also initializes any parent class properties - at the expense of possibly resetting already initialized properties. you can always extend the extension method to try and account for these cases.
- Resetting the properties in this manner works also outside constructor - anywhere in the program with the proper access.
- There's still the annoyance of having to add a line in the constructor - but it is just one line and will no require additional modifications if properties are added, removed or their type/default value is changed.

There you go,
have fun
Yours,
<><<br mode="hold" />Itai

GeneralRe: TIP: Autosetting properties in C# using DefaultValue attributes Pin
Mycroft Holmes20-Aug-11 16:48
professionalMycroft Holmes20-Aug-11 16:48 
GeneralRe: TIP: Autosetting properties in C# using DefaultValue attributes Pin
Itai Basel20-Aug-11 19:58
Itai Basel20-Aug-11 19:58 
GeneralRe: TIP: Autosetting properties in C# using DefaultValue attributes Pin
Itai Basel20-Aug-11 20:09
Itai Basel20-Aug-11 20:09 
GeneralRe: TIP: Autosetting properties in C# using DefaultValue attributes Pin
Mycroft Holmes20-Aug-11 22:35
professionalMycroft Holmes20-Aug-11 22:35 
GeneralRe: TIP: Autosetting properties in C# using DefaultValue attributes Pin
PIEBALDconsult20-Aug-11 19:57
mvePIEBALDconsult20-Aug-11 19:57 
GeneralRe: TIP: Autosetting properties in C# using DefaultValue attributes Pin
thatraja20-Aug-11 21:40
professionalthatraja20-Aug-11 21:40 
QuestionShowing Picture in Crystal Reports from Table Pin
M Riaz Bashir20-Aug-11 11:26
M Riaz Bashir20-Aug-11 11:26 
AnswerRe: Showing Picture in Crystal Reports from Table Pin
thatraja20-Aug-11 21:35
professionalthatraja20-Aug-11 21:35 
QuestionHow to decode Certificate Signing Request (CSR) in XP [modified] Pin
Petri Luoto20-Aug-11 9:03
Petri Luoto20-Aug-11 9:03 
QuestionSome advise on the following code Pin
venomation20-Aug-11 8:48
venomation20-Aug-11 8:48 
AnswerRe: Some advise on the following code Pin
PIEBALDconsult20-Aug-11 13:04
mvePIEBALDconsult20-Aug-11 13:04 
AnswerRe: Some advise on the following code Pin
Mycroft Holmes20-Aug-11 13:35
professionalMycroft Holmes20-Aug-11 13:35 
GeneralRe: Some advise on the following code Pin
venomation20-Aug-11 13:53
venomation20-Aug-11 13:53 
GeneralRe: Some advise on the following code Pin
PIEBALDconsult20-Aug-11 14:18
mvePIEBALDconsult20-Aug-11 14:18 
AnswerRe: Some advise on the following code Pin
BobJanova21-Aug-11 22:40
BobJanova21-Aug-11 22:40 
QuestionIs it possible to call Excel XLA function from .NET via Microsoft.Office.Interop? Pin
devvvy20-Aug-11 4:35
devvvy20-Aug-11 4:35 
QuestionPreRequesties on Client system Pin
jojoba201120-Aug-11 0:26
jojoba201120-Aug-11 0:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.