Cannot assign to '<this>' because it is read-only


  • Hi,

    I have an DataManager class that is able to return an object populated from the database based on the class type and primary key value.  I am trying to use that class in the constructor so that a user can simply pass in the ID and have an object loaded for them.  However, I cannot assign the object that my class return to the current class using the "this" keyword because it is readonly.  I also looked into Pointers, but C# does not allow pointers to user defined classes.  I know that I can assign individual property from the object return to the current class, but my preference is to avoid having all those extra lines of code.  This is the code that I am trying to execute:

    Person (long ID) {

    Person myPerson;

    myPerson = DataManager.Find<Person>(typeof(Person), ID);

    this = myPerson;



    Tuesday, March 28, 2006 5:23 PM


  • Yes it's true, you can't reassign this within C#. I would recommend adding a Static function to your class that does what you want.

    static Person getByID(long ID)

    return DataManager.Find<Person>(typeof(Person),ID);



    Then to use the function all you have to do is

    Person myPerson=Person.getByID(1234);

    Also it seems like you're using generics in your find function but are still passing in the type of your object to the function. This is redundant (and can be error prone). To eliminate the need to pass in the type to your function, you can do something like this.


    TObject Find<TObject>(long ID)

    TObject retVal;
    Type myType=typeof(TObject)
    //Do your data access and object initialization here.
    return retVal;


    Hope this helps

    Tuesday, March 28, 2006 6:09 PM