0

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?

JGFMK
  • 7,107
  • 4
  • 46
  • 80

1 Answers1

0

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;
Rafal
  • 11,105
  • 26
  • 49
  • Ok thanks. I'll give it a try. So I could do Regex? re;.. Then later assign null or a new Regex().. And use that syntax when defining the new list too? Just to emphasise the list may have a null a bit more clearly. – JGFMK Jun 29 '19 at 10:14
  • BTW: I am also thinking for the null instances I could just use `.*` as the regex... and be done with complexities of nulls.. – JGFMK Jun 29 '19 at 10:20
  • @JGFMK no you cannot use question mark with classes, just structs. You just need to accept that c# is different than Python and behaves differently. And yes 'accept all' or 'reject all' regex, depending on you business requirements, instead of null will make you code easier to write and understand. – Rafal Jun 29 '19 at 10:25