Search code examples
c#.netasp.net-mvc-3protectedaccess-specifier

How to make private property accessible in MVC3


I'm using Mvc3 and NHibernate I have a class called Activation code like following:

public virtual int LoginAccountId { get; set; }
protected virtual string ActivatedCode { get; set; }
protected virtual DateTime ActivationDate { get; set; }

I want to access this field in a controller lik

ActivationCode code=new ActivationCode();
code.ActivatedCode="abc";

but not able to get it. why?


Solution

  • The property is protected which means you can access it only from inside the class or inside one of it's inheritances.

    public class ActivationCode{
        public virtual int LoginAccountId { get; set; }
        protected virtual string ActivatedCode { get; set; }
        protected virtual DateTime ActivationDate { get; set; }
        
        public void Foo(){
            var x = this.ActivatedCode; // Valid
        }
    

    }

    public class Foo{
        new ActivationCode().ActivatedCode //Invalid access
    }
    

    You can change the properties from protected to public just like with LoginAccountId.

    Read MSDN article about protected:

    The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.

    A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type. For example, consider the following code segment:

    Update:

    The ActivationCode class should look like this:

    public class ActivationCode
    {
        public virtual int LoginAccountId { get; set; }
        public virtual string ActivatedCode { get; set; }
        public virtual DateTime ActivationDate { get; set; }
    }