Need a refresher course on property access...

Posted by Code Sherpa on Stack Overflow See other posts from Stack Overflow or by Code Sherpa
Published on 2010-05-26T16:46:38Z Indexed on 2010/05/26 16:51 UTC
Read the original article Hit count: 221

Filed under:
|

Hi.

I need help with accessing class properties within a given class.

For example, take the below class:

public partial class Account
    {
        private Profile _profile;
        private Email _email;
        private HostInfo _hostInfo;

        public Profile Profile
        {
            get { return _profile; }
            set { _profile = value; }
        }

        public Email Email
        {
            get { return _email; }
            set { _email = value; }
        }

        public HostInfo HostInfo
        {
            get { return _hostInfo; }
            set { _hostInfo = value; }
        }

In the class "Account" exists a bunch of class properties such as Email or Profile. Now, when I want to access those properties at run-time, I do something like this (for Email):

    _accountRepository = ObjectFactory.GetInstance<IAccountRepository>();
    string username = Cryptography.Decrypt(_webContext.UserNameToVerify, "verify");
    Account account = _accountRepository.GetAccountByUserName(username);

    if(account != null)
    {
        account.Email.IsConfirmed = true;

But, I get "Object reference not set..." for account.Email... Why is that? How do I access Account such that account.Email, account.Profile, and so on returns the correct data for a given AccountId or UserName.

    Here is a method that returns Account:

public Account GetAccountByUserName(string userName)
{
    Account account = null;

    using (MyDataContext dc = _conn.GetContext())
    {
        try
        {
            account = (from a in dc.Accounts
                       where a.UserName == userName
                       select a).FirstOrDefault();
        }
        catch
        {
            //oops
        }
    }

    return account;

}

The above works but when I try:

 account = (from a in dc.Accounts
               join em in dc.Emails on a.AccountId equals em.AccountId
               join p in dc.Profiles on em.AccountId equals p.AccountId
               where a.UserName == userName
               select a).FirstOrDefault();

I am still getting object reference exceptions for my Email and Profile
properties. Is this simply a SQL problem or is there something else I need to be doing to be able to fully access all the properties within my Account class?

Thanks!

© Stack Overflow or respective owner

Related posts about c#

Related posts about properties