简体   繁体   中英

Is there the equivalent of Python 3's Optional for generics in C#?

I want to have a List of a type Regex. But the list can have None (or null).

So I'd like the syntax List<Regex|Null> or something similar.

  • There is a blog post here that has the same concept.

But I'm hoping there may be something baked into C# I am overlooking.

  • Python 3 has Optional . Does C# have anything like that?

  • I did see something about using a question mark here . But it didn't give an example that made sense to me.


new T?(x)

I have seen:

  • a post entitled "Discriminated Unions" here that sort of hits the point of what I am after.
  • Also this entitled "Multiple generic Types in one List" one .

I also think there are often Union classes for this kind of thing, having seen similar SO posts


What would be the simplest C# code to define such a Typed generic List, and add either null or a Regex to it?

Actually you do not have to do anything to get nulls in such list:

var list = new List<Regex>();
list.Add(null);

This is because Regex is a class and this is how it works.

var regex = CreateMyRegex();
list.Add(regex);

Regardless of what the method CreateMyRegex returns, null or instance, it will get added to list.

Actually currently you cannot make it the other way around - forbid nulls in such list. There is a possibility that this will be possible in C# 8.

If you would like to do this with structs you can do it as well:

var list = new List<int?>();
list.Add(null);

The question mark syntax is not restricted to generics in c#, you can make nullable structures as any other variable type:

int? number = null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM