Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an open type be a struct?

I have some types that are structs for performance reasons and have some commonality. I would like to know if I can refactor them to be open type structs -- and if I should expect any problems if I can.

like image 550
Cort Avatar asked Jan 20 '23 21:01

Cort


2 Answers

Yes, you can. Some of the generic types provided by the framework library, such as KeyValuePair<TKey, TValue>, are indeed structs.

like image 115
Frédéric Hamidi Avatar answered Jan 30 '23 14:01

Frédéric Hamidi


UPDATE: Apparently by "open type" you do not mean the same thing as the C# specification definition of "open type". You mean "generic type".

Yes, structs can be generic.

To answer the second part of your question: I don't know what sorts of "problems" you have in mind. Can you give me an example of something you find problematic?


Original answer, assuming that you were actually asking about open types:

The C# specification is clear on this point:

• A type parameter defines an open type.

• An array type is an open type if and only if its element type is an open type.

• A constructed type is an open type if and only if one or more of its type arguments is an open type. A constructed nested type is an open type if and only if one or more of its type arguments or the type arguments of its containing type(s) is an open type.

So there you go. A struct type is an open type if and only if it, or its enclosing type, is a generic type with an open type for one of its type arguments. For example:

struct S<T>
{
  S<T> s1; // open struct type
  Nullable<S<T>> s2; // another open struct type
}

class O<V>
{
  class C<U> where U : struct
  {
    struct R
    {
      U u; // open type constrained to be value type
      R r1; // open struct type; this is O<V>.C<U>.R
      O<V>.C<S<U>>.R r2; // another open struct type.
      O<int>.C<S<V>>.R r3; // another open struct type 
    }
  }
}

We can keep on making open struct types all day.

like image 24
Eric Lippert Avatar answered Jan 30 '23 13:01

Eric Lippert