Ahmadali Shafiee
Ahmadali Shafiee

Reputation: 4657

How to modify the class from it's extension method?

I'm trying to create two method to serialize/deserialize classes using Json.Net and save/load them to/from file and this is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.Text.RegularExpressions;

namespace System
{
    public static class SystemExtentions
    {
        public static void SaveToFile(this object data, string FileName)
        {
            using (StreamWriter writer = new StreamWriter(FileName))
            {
                string s = JsonConvert.SerializeObject(data);
                writer.Write(s);
                writer.Close();
            }
        }

        public static void LoadFromFile<t>(t date,string FileName)
        {
            using (StreamReader reader = new StreamReader(FileName))
            {

                data = JsonConvert.DeserializeObject<t>(reader.ReadToEnd());
                reader.Close();
            }
        }
    }
}

but in LoadFromFile method data = JsonConvert.DeserializeObject<t>(reader.ReadToEnd()); doesn't work! it means that if I had this code:

Class1 c1=new Class1();
c1.LoadFromFile<Class1>("c1.clf");

after the code runs the properties of c1 doesn't change.

I want to Know why and is there any solution to modify the class or set it's properties(deserialize it!) from LoadFromFile in independent(independent to class type and properties)(dynamically) way?

Upvotes: 1

Views: 335

Answers (1)

jeroenh
jeroenh

Reputation: 26782

Your LoadFromFile method takes a parameter of type t that your are assigning to inside the method. This does not make sense. Instead, use a return value:

public static T LoadFromFile<T>(string fileName)
{
    using (StreamReader reader = new StreamReader(FileName))
    {
       return JsonConvert.DeserializeObject<T>(WpfApplication.Helper.Decrypt(reader.ReadToEnd()));
    }
}

This would allow you to use this code like this:

Class1 c1 = LoadFromFile<Class1>("c1.clf");

Side note: no need to explicitly close a streamreader if you use the using construct

Upvotes: 5

Related Questions