Home > OS >  use 1 line of code instead of the use the same code
use 1 line of code instead of the use the same code

Time:02-22

I have code like this:

string FileName = "Users.json";
var DeserializeOptions = new JsonSerializerOptions { AllowTrailingCommas = true };
string jsonstring = File.ReadAllText(FileName);
var result = JsonSerializer.Deserialize<Root>(jsonstring, DeserializeOptions);

Root is list of 2 objects: Monsters and People. I use these 4 lines of code in my win forms program more than 10 times. Is it possible to change this code for class and use in other .cs files using shorter code?

CodePudding user response:

Sure - put your code into a method:

internal static class MyUtilities
{
    public static Root DoMyStuff()
    {
        string FileName = "Users.json";
        var DeserializeOptions = new JsonSerializerOptions { AllowTrailingCommas = true };
        string jsonstring = File.ReadAllText(FileName);
        return JsonSerializer.Deserialize<Root>(jsonstring, DeserializeOptions);
    }
}

Depending on your use case and the case your code varies across those different instances (not sure whether it is 100% the same, or uses different filenames, for example), you may want to accept some of those values as parameters.

In any case, you can then replace all of your code by single lines like this:

var result = MyUtilities.DoMyStuff();
  • Related