Null out parameters in C#?

2019-02-21 08:45发布

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 long and nasty looking to cover lots of the formatting.

But TryParse requires an "out" parameter and since I just want to do a validation format check I don't need the actual result.

So I am left with a variable that holds the "out" result and am to do nothing with it. Is there a way so I don't have to do a out parameter?

So I get rid of this warning and stop having a variable just flying around.

6条回答
smile是对你的礼貌
2楼-- · 2019-02-21 09:04

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]

查看更多
一纸荒年 Trace。
3楼-- · 2019-02-21 09:06

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.

查看更多
神经病院院长
4楼-- · 2019-02-21 09:07

With C#7 (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);
查看更多
我命由我不由天
5楼-- · 2019-02-21 09:08

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...

查看更多
一夜七次
6楼-- · 2019-02-21 09:11

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 :)

查看更多
女痞
7楼-- · 2019-02-21 09:18

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()
  }
查看更多
登录 后发表回答