Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "long?" really a struct?

Tags:

c#

nullable

By definition Nullable<> is a struct but when I call some generic function, it behaves like it's an object.

class GenController
{
    public void Get<T>(T id) where T : struct
    {
        Console.Write("is struct");
    }

    public void Get(object obj)
    {
        Console.Write("is object");
    }
}

long param1 = 1234;
new GenController().Get(param1);
// output is "is struct" as expected

long? param2 = 1234;
new GenController().Get(param2);
// output is "is object"
// obj seen at debug time as "object {long}"
// expected "is struct"

So the parameter is seen as an object instead of a struct.

Any idea of what's happening, am I misunderstanding the meaning of struct?

Is there a way to dispach Nullable<T> or T and object as different kind of parameters?

like image 935
sinsedrix Avatar asked Nov 09 '20 09:11

sinsedrix


People also ask

How big should a struct be?

NET uses at least 24 bytes of memory (IIRC), so if you made your structure much larger than that, a reference type would be preferable.

How many bytes is a struct in C++?

Contrary to what some of the other answers have said, on most systems, in the absence of a pragma or compiler option, the size of the structure will be at least 6 bytes and, on most 32-bit systems, 8 bytes. For 64-bit systems, the size could easily be 16 bytes.


2 Answers

Nullable<T> is definitely a struct.

Your question is more about the where T : struct generic type constraint, than it is about Nullable<T>.

From the docs:

where T : struct: The type argument must be a non-nullable value type.

long? is a nullable value type, and so isn't permitted by the where T : struct constraint.

like image 126
canton7 Avatar answered Oct 12 '22 22:10

canton7


To answer the question:

  • Nullable<T> is a struct
  • The struct constraint only allows not nullable structs.

With that said, you can specify that the parameter is nullable, like this:

public void Get<T>(T? id)
    where T: struct
{
    Console.Write("is nullable struct");
}

That would be one more overload to capture nullable structs.

like image 37
Theraot Avatar answered Oct 13 '22 00:10

Theraot