Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check whether a struct has been instantiated? [duplicate]

Tags:

c#

null

struct

I have a struct that (for the purposes of this question) pretty much mimics the built in Point type.

I need to check that it has been instantiated before using it. When it was Point, I could do this:

if (this.p == null) 

But that now generates the following error:

Operator '==' cannot be applied to operands of type 'ProportionPoint' and '<null>'

How can I compare my struct against null? Is there another way to check for instantiation?

like image 786
Tom Wright Avatar asked Oct 01 '12 12:10

Tom Wright


People also ask

How do you check if a struct has been initialized?

The only way you could determine if a struct was initialized would be to check each element within it to see if it matched what you considered an initialized value for that element should be.

Can a struct be instantiated?

Unlike classes, structs can be instantiated without using the New operator. If the New operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized.

Are structs copied by value?

We can now modify every property of those variables without affecting the other object, because the Dog struct contains basic types, which are copied by value.

Is struct null?

In C# a struct is a 'value type', which can't be null.


1 Answers

A struct is a value type - it's never null.

You can check against default(ProportionPoint), which is the default value of the struct (e.g. zero). However, for a point, it may be that the default value - the origin - is also a "valid" value.

Instead you could use a Nullable<ProportionPoint>.

like image 101
Rawling Avatar answered Sep 22 '22 05:09

Rawling