properties problem
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Thread: properties problem

  1. #1
    Join Date
    Jan 2010
    Posts
    11

    Question properties problem

    Hi guys,

    just joined this forum and it seems to real cool place to ask some questions although they may be weird .Just new to C# .

    Ok so can someone please tell me that if the main aim of the private access specifier is to protect the field from being modified by the object or other classes why do the properties allow it.

    like we have some private field say int m now we declare a public property and allow it to set value of m and now the value of m can be changed by the object......so i want to know that how encapsulation concept is not violated over here .


    i am new to c# so guys don't mind if i have asked something stupid and if u feel so still do reply .

    Thanks
    Sid

  2. #2
    Arjay's Avatar
    Arjay is online now Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    11,295

    Re: properties problem

    Probably the best thing you can do is work through a few C# books. They're great at explaining how these sorts of things work.

    At any rate, here's my take:

    1) Private prevents public access or any derived class access. For example, if you declare a field variable in a base class as private and then derived from that class, you won't be able to access the field in the derived class. If you need to access the field from derived classes, declare the field as protected. When you instantiate the class, only fields, properties, and methods declared as public can be accessed from outside the class.

    2) In general, encapsulation means whenever crossing a boundary of some sort. A boundary can be from a base class to a derived class. Another boundary is when a class is instantiated, only its public members are exposed - the rest are said to be encapsulated.

  3. #3
    Join Date
    Mar 2007
    Posts
    59

    Re: properties problem

    Not really, a property is exactly like a method. The advantage is if you change the internal object, the properties and methods signature doesn't need to change. Usually property and memver variable are mapped to 1, but it's not always the case.

    also, if you want, you can set also the access level of a property if you want:

    Code:
    int M { get; private set; }
    or just not define a set accessor.


    Hope it answer your question.

  4. #4
    Join Date
    Jun 2008
    Posts
    2,477

    Re: properties problem

    Because properties encapsulate the action of getting and setting the variable. This is something beginners stumble over because most books/classes teach properties that look like this:

    Code:
    private string _name;
    public string Name
    {
        get { _name = value; }
        set { return _name; }
    }
    So, it is no wonder that beginners ask the question "what is the point in all of this? Seems to me like bunch of extra syntax for 'public string Name;'". Well, you are right; there is no functional difference in between those two. However, what if we expect name to never be null? If Name were simply a public field, users of the code could do this:

    Code:
    someObj.Name = null;
    Oops! Now any code within the class that assumes Name will never be null has a bug. However, if Name is a property we can validate the input before setting the private variable.

    Code:
    private string _name;
    public String Name
    {
        get { return _name; }
        set 
        {
            if( value != null )
            {
                _name = value;
            }
            else
            {
                throw new ArgumentNullException( "'Name' cannot be null." );
            }
        }
    }
    Now we control the value values for Name inside of the class.

    Also, what if we wanted Name to be a readonly variable? We could not accomplish that with a simple public field, but we can with a property:

    Code:
    private string _name;
    public String Name
    {
        get { return _name; }
        // no setter!
    }
    The important thing to remember is that creating a property is functionally equivalent to this, it simply gives us a nicer syntax to use:

    Code:
    private string _name;
    
    public string GetName( )
    {
        return _name;
    }
    
    public void SetName( string value )
    {
        // error checking
        _name = value;
    }
    We are trying to provide a mechanism which can react to the retrieval or setting of a field.

    Also realize that properties are not only useful for error checking, but are also commonly used to take some action upon the setting of a variable. For example, if we created our own control class which painted a number to the screen, it would be appropriate to repaint the control when the number to draw is changed. Otherwise the user will not see the change immediately, but will instead have to wait for the OS to tell the window to refresh.

    Code:
    using System.Windows.Forms;
    using System.Drawing;
    
    class MyControl : Control
    {
        private int _numToDisplay;
        public int NumToDisplay
        {
            get { return _numToDisplay; }
            set
            {
                // only repaint if the value has changed
                if( _numToDisplay != value )
                {
                    _numToDisplay = value;
                    Invalidate( );  // calls OnPaint eventually
                }
            }
        }
    
        protected override void OnPaint( PaintEventArgs e )
        {
            base.OnPaint( e );
            e.Graphics.DrawString( NumToDisplay.ToString( ), this.Font, Brushes.Black, new PointF( 0, 0 ) )
        }
    }
    Properties in C# are simply an example of a new language implementing commonly used patterns in the syntax itself. The pattern here is just creating methods to get and set a private field.

    EDIT: Wow, it took me so long to write that I got Ninja'd twice

  5. #5
    Join Date
    Jan 2010
    Posts
    11

    Re: properties problem

    Thanks guys ..quick response.....and that was so easy to understand ....i am sure i will be asking more stuff no matter if that's stupid also ..

  6. #6
    Join Date
    Jan 2010
    Posts
    11

    Re: properties problem

    Guys one thing more i wanna know that i have read that in polymorphism we can pass the objects even if it expects a different object of the derived class.......can someone please show me some simple code showing how objects can be passed as method arguments and how is it useful and what exactly is polymorphism.......i have read many books and i know how it works just could'nt get the object thing that we can pass different object when it expects a different object.


    Thanks
    Sid

  7. #7
    Join Date
    Jun 2008
    Posts
    2,477

    Re: properties problem

    Polymorphism is a mechanism by which objects may be manipulated through their interface instead of their implementation.

    Every class definition defines an interface through its public methods. Sometimes it is useful to treat objects opaquely through their interface alone. Instead of showing you an Animal, Dog, and a Cat class and go on to display how they can all be treated as Animal objects, I will instead give you a real world example.

    If you have done any WinForms programming in C# at all you will already know that each form has a public property named "Controls". This is a collection of Control objects, and more importantly, a collection of objects that may be treated as their base class "Control" while actually being an object of a different underlying type. It allows us to do things like the following:

    Code:
    class MyControl : Control
    {
    }
    
    class MyForm : Form
    {
        public MyForm( )
        {
            this.Controls.Add( new Label( ) );
            this.Controls.Add( new TextBox( ) );
            this.Controls.Add( new MyControl( ) );
        } 
    }
    We are able to add any object that derives from "Control" into the "Controls" object collection. Within the implementation of the "Form" class the different objects are treated as "Control" objects, and that interface provides all of the mechanisms needed by the Form to position, display, and update the objects.

  8. #8
    Join Date
    Jan 2010
    Posts
    11

    Question Re: properties problem

    @BigEd

    My understanding of polymorphism is that suppose we have some function say draw and i inherit the class containing draw and then i make draw as virtual in base class and then override it in derived class then make objects and at runtime the objects will be connected to their respective draw method and we can pass objects of derived class when some function expects a base class object. and this is polymorphism ie one object many forms .

    I could'nt understand your answer completely so if you can take into account my understanding of polymorphism and then just explain it to me accordingly then that what be really cool.I could'nt understand that interface thing ..i did'nt understanding this passing of object concept also....that we can pass derived class objects but what is the use of this and can someone please show me the practical implementation of this concept

    hope you can see now what level of understanding i am at and tell me accordingly.

    Thanks
    Sid
    Last edited by sidhu688; January 30th, 2010 at 10:08 PM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center