none
Best way to access field value from another class RRS feed

  • Question

  • Hi ,

    Suppose i have two classed ClassA and ClassB .

    In

    class A

    {

           private string _dataValue;

            public ClassA(string calculatedValue)
            {
                DataValue= calculatedValue;
            }

        public string DataValue
            {
                get { return _dataValue; }
                private set { _dataValue= value; }
            }

    }

    In ClassB,I have access from get value of _dataValue from classA .

    var fromA=new from classA()...

    var x=fromA.DataValue

    ---------------------------------

    here i just want know what will be the difference in performance and programming standard if i try to access from Class A like this

    classA
    {

           public readonly string DataValue;

            public classA(string calculatedValue)
            {
                DataValue= calculatedValue;
            }

    }

    Thanks

    Binaya Acharya .

    Sunday, November 4, 2012 9:17 AM

Answers

  • For performance reasons the differences are really negligible.

    An old and good object oriented principle is Encapsulation . A way to achieve it is to not expose the inner type.

    If you have ever wanted to change the type of DataValue in ClassA the public field solution Could cause that all ClassB objects would have to change also.

    In C# auto properties are most used and fit your purpose just fine.

            public class ClassA
            {
                public ClassA(string calculatedValue)
                {
                    this.DataValue = calculatedValue;
                }
    
                public string DataValue { get; private set; }
            }


    Sunday, November 4, 2012 1:44 PM

All replies

  • For performance reasons the differences are really negligible.

    An old and good object oriented principle is Encapsulation . A way to achieve it is to not expose the inner type.

    If you have ever wanted to change the type of DataValue in ClassA the public field solution Could cause that all ClassB objects would have to change also.

    In C# auto properties are most used and fit your purpose just fine.

            public class ClassA
            {
                public ClassA(string calculatedValue)
                {
                    this.DataValue = calculatedValue;
                }
    
                public string DataValue { get; private set; }
            }


    Sunday, November 4, 2012 1:44 PM
  • Thank you KeeDjik ,

    Thank you for your information .

    Monday, November 5, 2012 5:26 AM