PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, June 25, 2022

[FIXED] How to solve a "cannot assign to 'this' as it is readonly" error c#

 June 25, 2022     c#, compiler-errors, datatable, json, this     No comments   

Issue

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));
        }
    }
}

Solution

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);



Answered By - Somar Zein
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing