Properties with Methods

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • scott1010
    New Member
    • Jul 2009
    • 6

    Properties with Methods

    Hello,

    I am sure this is easy, but I am not sure what to search for but I am looking to be able to do something like:

    Code:
    MyObject.MyProperty = "1234F";
    MyObject.MyProperty.IsValid();
    MyObject.MyProperty.MyOtherMethod();
    I want to be able to add methods to properties of different types such as Strings, Ints and GUIDs.

    Cheers,
    Scott
  • cloud255
    Recognized Expert Contributor
    • Jun 2008
    • 427

    #2
    Hi

    Well it is pretty straight forward, you have to create a class which has properties (variables) and methods (functions).

    Hope this helps, feel free to post if the above msdn links don't help you achieve what you want to.

    Comment

    • Curtis Rutland
      Recognized Expert Specialist
      • Apr 2008
      • 3264

      #3
      So consider this code:
      Code:
      //CLASS B
      public class B
      {
        public float Value { get; set; }
        public bool IsValid
        {
          get
          {
            //use whatever logic you need here
            return Value > 0;
          }
        }
        public void MyOtherMethod()
        {
          //do whatever
        }
      }
      
      
      ///CLASS A
      public class A
      {
        public B MyProperty { get; set; }
        
        public A ()
        {
          MyProperty = new B();
        }
      }
      You create a class "A" that has all the properties you need. Then you create your class "B" which has a property of type "A". That should do what you need.

      Note that in my example, "IsValid" is a property, not a method, and wouldn't need () when called.

      Comment

      • Christian Binder
        Recognized Expert New Member
        • Jan 2008
        • 218

        #4
        Hi,

        you could also use Extension-Methods to solve your problem if you are using .NET 3.5.
        With this you can add Methods to the Integer-Type for example, wo you would be able to do:
        Code:
        int myInt = 0; 
        myInt.IsValid()
        But i would prefer using something like insertAlias' example. You could overload the Implicit Conversion Operator, so you could directly assign the float like you did in your example
        MyObject.MyProp erty = "1234F";
        instead of using the .Value-property of class B

        Comment

        Working...