Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable local values in c# - a specific use case

I know that this general topic has been discussed here before. What I am interested in is if there is a good solution for my specific case:

I have a command line tool like this (simplified):

static void Main(string[] args)
{
    if (args.Length < 2)
    {
        Console.WriteLine("Usage: MyTool <InputFolder> <OutputFolder>");
        return;
    }

    string inputFolder = args[0];
    string outputFolder = args[1];

    // ...
}

I assign names to the argument values to make the code more readable. I would also like to express that these values will not be modified later.

Neither const nor readonly can be used here because the values is not known at compile time and because they are local 'variables' and not class members.

So how could I make this code more expressive and readable?

like image 339
Frank Puffer Avatar asked Mar 06 '23 02:03

Frank Puffer


2 Answers

My proposition is creating a class holding your variables

public class Immutable
{
    public Immutable(string[] args)
    {
         InputFolder = args[0];
         OutputFolder = args[1];
    }
    public readonly string InputFolder;
    public readonly string OutputFolder;
}

then

var m = new Immutable(args)
like image 148
Antoine V Avatar answered Mar 07 '23 17:03

Antoine V


How about the C# 7.2 ref readonly?

static void Main(string[] args)
{
    if (args.Length < 2)
    {
        Console.WriteLine("Usage: MyTool <InputFolder> <OutputFolder>");
        return;
    }

    ref readonly var inputFolder = ref args[0];
    ref readonly var outputFolder = ref args[1];
}
like image 40
Magnus Avatar answered Mar 07 '23 16:03

Magnus