Search code examples
c#.net-core.net-standard-2.0

What does the error "argument is value while parameter is declared as in" mean?


In a netstandard 2.0 application, I have the following method that is part of a static class:

public static class Argument 
{    
    /// <param name="inst">Inst.</param>
    /// <param name="instName">Inst name.</param>
    /// <exception cref="ArgumentException">
    /// Thrown if :
    /// <paramref name="inst" /> is not specified in a local time zone.
    /// </exception>
    public static void ThrowIfIsNotLocal(in DateTime inst, string instName)
    {
        if (inst.Kind != DateTimeKind.Local)
            throw new ArgumentException(instName, $"{instName} is not expressed in a local time-zone.");
    }
}

In my program that is running .netcore 2.0, I have the following line that generates an error:

Argument.ThrowIfIsNotLocal(DateTime.Now, "timestamp");

argument is value while parameter is declared as in

Why is DateTime.Now causing the error to appear?


Solution

  • The method signature states that the parameter needs to be passed by reference, not by value. That means that you need to have some sort of storage location that can be referenced to pass into that method.

    The result of a property getter is not a variable; it's not something that you can have a reference to. It's just a value, hence the error message.

    You need to both have a variable, rather than just a value, and also use the in keyword when calling the method to indicate that you're intending to pass a reference to the variable, rather than just the value of the variable.

    var now = DateTime.Now;
    ThrowIfIsNotLocal(in now, "");
    

    Of course, there's no real reason to pass this variable by reference in the first place. I'd suggest not doing so, and simply passing the parameter by value. That way callers won't need to go through all of this when they just have a value, not a variable.