DataTable NullReferenceException: Object reference not set to an instance of an object System.Data.DataTable.get_TableName ()

I am looking to learn to use DataTable object for organizing data then exporting to csv from the DataTable but for some reason I am not able to access the object that I create. I went ahead and imported the System.Data.dll and tried creating the datatable in different parts of the script with global or local references, adding columns rows,'ve tried restarting the project, creating new project none of which help.

I am stuck. Any pointers will be greatly appreciated!

using System.Collections;
using System.Collections.Generic;
using System.Data ;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {

	public DataTable dt = new DataTable ();

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		Debug.Log (dt.TableName);
	}
}

Issue was solved by changing my .NET target from 3.5 to 4.X.

These are found in The Edit Menu > Project Settings >Player then in the inspector: API Compatibility Level (changing “Scripting Runtime Version” might also be needed)

MonoBehaviour classes in Unity have some rules that you should be aware of because you’re breaking one of them in your code. If you want to initialize data you should do so in the methods that the MonoBehaviour class provides, Start and Awake are the most common ones. If it isn’t a primitive type like floats, ints, bools, etc. you should not initialize fields inline with their declaration. You should also not have constructors on MonoBehaviour classes. Take a look at the comment on top of the Start method, “Use this for initialization” so do exactly that.

void Start () {
    dt = new DataTable();
}

This should solve your problem. Hope this helps!

I really wanted your answer to work.
I originally tried to initialize in Awake but that didn’t help. I then tried to create local version of the DataTable and still couldn’t get that to work. I have seen something like this before but it always fixed itself after restarting or deleting the Library directory or changing the build platform. So far I still get the the same error even with trying the below two versions just now.

using System.Collections;
using System.Collections.Generic;
using System.Data ;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {

	public DataTable dt;

	// Use this for initialization
	void Start () {
		DataTable dt = new DataTable ();
	}
	
	// Update is called once per frame
	void Update () {
		Debug.Log (dt.TableName);
	}
}

using System.Collections;
using System.Collections.Generic;
using System.Data ;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour {

	//public DataTable dt;

	// Use this for initialization
	void Start () {
		//DataTable dt = new DataTable ();
	}
	
	// Update is called once per frame
	void Update () {
		DataTable dt = new DataTable ();
		Debug.Log (dt.TableName);
	}
}