user2780265
user2780265

Reputation: 53

update data on file change?

    public DataUpdater(string file, ref DataTable data)
    {
        FileSystemWatcher fileWatcher = new FileSystemWatcher();
        fileWatcher.Path = Path.GetDirectoryName(file);
        fileWatcher.Filter = Path.GetFileName(file);
        fileWatcher.NotifyFilter = NotifyFilters.LastWrite;
        fileWatcher.Changed += (sender, e) =>
            {
                data = CSVParser.ParseCSV(file);
            };
    }

Hello, i'm trying to update a data table variable when a file changes but the output says i cant have a ref or out in the changed event. please help

Upvotes: 2

Views: 104

Answers (1)

olydis
olydis

Reputation: 3310

Okay what you are trying looks like a reasonable idea, but you cannot set values to ref parameters from within lambdas. Why? Well, a ref parameter gives you the right to access the provided variable as long as the method runs. Since, in fact, there is no way to know when the lambda runs, writing to this variable inside of it is therefore not allowed - it would be a backdoor for unlimited writing access to that variable.

Possible solution:

Change the signature of DataUpdater to something that gives permanent access to your DataTable.

public DataUpdater(string file, Action<DataTable> setter);

Call this constructor via new DataUpdater(..., x => targetTable = x) and change the line inside the lambda to setter(CSVParser...);

I hope this makes sense ;)

Upvotes: 1

Related Questions