Home > Enterprise >  How to solve a "cannot assign to 'this' as it is readonly" error c#
How to solve a "cannot assign to 'this' as it is readonly" error c#

Time:04-06

I am creating a class that creates my own custom table using DataTable.

I want it so that if a json file with the DataTable's info is on my computer; the code will put the json file into that instance of the object (done in the constructor)

This is how i am trying to do it

public Table(string jsonfile)
    {
        if(File.Exists(jsonfile))
        {
            this = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));
            return;
        }
        formatRegisterTable(jsonfile);
    }

this line is causing the error

this = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));

How can I do this without the error?

The full code of the class if needed:

using System.IO;
using System.Data;
using Newtonsoft.Json;

namespace abc.classess._table
{
     class Table
    {
        public DataTable mTable = new DataTable("table");
        private DataColumn mColumn;
        private DataRow mRow;
        

        public Table(string jsonfile)
        {
            if(File.Exists(jsonfile))
            {
                this = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));
                return;
            }
            formatRegisterTable(jsonfile);
        }

        private void formatRegisterTable(string jsonfile) 
        {
            //formatting table code

            File.WriteAllText(jsonfile,JsonConvert.SerializeObject(this));
        }
    }
}

CodePudding user response:

Something like this should solve your problem:

Inside you Table class create the following function:

 public static Table Create(string jsonfile)
 {
       if (File.Exists(jsonfile))
       {
            Table table = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));
            return table;
        }
        
        return new Table(jsonfile);
  }

Your table constructor should look now like this:

 public Table(string jsonfile)
 {
    formatRegisterTable(jsonfile);
 }

Then you can use it in ur code var newTable = Table.Create(jsonFile);

  • Related