can we have a nullable field in the struct

J

James

hello,

can we have a nullable type field in the struct ?
struct Employee
{
nullable<string> firstName =null;
}
we can't initialize a field in a struct so is there any possibility
that we can have a nullable field in the struct.
can anyone please help me out regarding this

Thanks,
James
 
N

Nicholas Paldino [.NET/C# MVP]

James,

You can't use string as the type parameter for Nullable<T> because there
is a constraint making it a structure. This makes sense, since reference
types can be null.

If you just make it a string, by default, the field will be null when
the structure is constructed. You don't need to initialize it, you just
have to declare it.
 
X

xc

hi Nicholas,

"You can't use string as the type parameter for Nullable<T> because there
is a constraint making it a structure"

then, when it should be good to use Nullable<T>,
I think for classes there is no need at all to use Nullable<T>

thanks, Carlos
 
N

Nicholas Paldino [.NET/C# MVP]

Carlos,

That's basically what I was saying. T must be a value type when using
it in Nullable<T>. For reference types (like string), it makes no sense
because you can just set it to null anyways.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top