Null out parameters in C#?

后端 未结 6 1134
深忆病人
深忆病人 2021-01-17 11:19

After reading on stackoverflow that in the case of checking the format of a DateTime you should use DateTime.TryParse. After trying some regex expressions they seem to get l

相关标签:
6条回答
  • 2021-01-17 11:45

    No. You can't get rid of the variable but you shouldn't get a compiler warning either.

    Passing a variable as out is "using" the variable. The compiler will not issue a warning because of that.

    0 讨论(0)
  • 2021-01-17 11:49

    TryParse is a better option. Its just a variable that is wasted. Other options include using the Convert.ToDateTime() within a try-catch block. But again that would not be efficient because try-catch blocks are meant to be heavy. The next option is regex. This is a better solution. I guess this gives you the result instantly than compared to the others.

    You can very well wrap the method like Kim Gräsman said...

    0 讨论(0)
  • 2021-01-17 11:50

    With C#7.0 (since August 2016) you can use the out var construct, and then just ignore the new var in subsequent code.

    bool success = DateTime.TryParse(value, out var result);
    

    If you truly do not care about the value of the result, use discards:

    bool success = DateTime.TryParse(value, out _);
    
    0 讨论(0)
  • 2021-01-17 11:52

    Nope. I'd wrap it in a method somewhere to keep the noise out of the main flow:

      bool IsValidDate(string value)
      {
         DateTime result;
         return DateTime.TryParse(value, out result); //result is stored, but you only care about the return value of TryParse()
      }
    
    0 讨论(0)
  • 2021-01-17 11:58

    If you are using .NET 3 and above, you could always create an Extension method?

    public static bool IsValidDate(this string value)
    {
      DateTime date = DateTime.Null;
      return DateTime.TryParse(value, out date);
    }
    

    [Edited to rename the method name to a more appropriate one]

    0 讨论(0)
  • 2021-01-17 11:59

    I'm not suggesting you actually do this, but you could use a single helper class to make this easy for all out parameters:

    public static class OutHelper<T>
    {
        [ThreadStatic]
        public static T Ignored;
    }
    

    Then you can call:

    if (DateTime.TryParse(text, out OutHelper<DateTime>.Ignored))
    

    It's horrible, uses a public mutable field, and if your application is also executing with some malicious code, it gives that code access to the last value you've parsed... but it should work :)

    0 讨论(0)
提交回复
热议问题