Altering lazy-loaded object's private variables

Posted by Kevin Pang on Stack Overflow See other posts from Stack Overflow or by Kevin Pang
Published on 2010-04-03T13:27:15Z Indexed on 2010/04/03 13:33 UTC
Read the original article Hit count: 319

Filed under:
|
|

I'm running into an issue with private setters when using NHibernate and lazy-loading. Let's say I have a class that looks like this:

public class User
{
    public int Foo {get; private set;}
    public IList<User> Friends {get; set;}

    public void SetFirstFriendsFoo()
    {
        // This line works in a unit test but does nothing during a live run with
        // a lazy-loaded Friends list
        Users(0).Foo = 1; 
    }
}

The SetFirstFriendsFoo call works perfectly inside a unit test (as it should since objects of the same type can access each others private properties).

However, when running live with a lazy-loaded Friends list, the SetFirstFriendsFoo call silently fails. I'm guessing the reason for this is because at run-time, the Users(0).Foo object is no longer of type User, but of a proxy class that inherits from User since the Friends list was lazy-loaded.

My question is this: shouldn't this generate a run-time exception? You get compile-time exceptions if you try to access another class's private properties, but when you run into a situation like this is looks like the app just ignores you and continues along its way.

© Stack Overflow or respective owner

Related posts about c#

Related posts about nhibernate