moteutsch
moteutsch

Reputation: 3841

Object property containing nothing as default in C#

In a class I have a property:

public Move plannedMove;

By default I would like it to contain nothing, so that I can test if it is set in my code in some some way similar to

if(!plannedMove)

Or something like that. I also want to be able to unset it so that it is blank to being empty. How can I do this?

Just in case I'm going about this totally wrong I will explain my original problem: my Player object needs to be able to have an optional precalculated move. In a method GetMove it needs to either return the precalculated move, or calculate one. How can I do this?

EDIT: Yikes, forgot to mention Move is a struct.

Upvotes: 0

Views: 93

Answers (5)

Cheng Chen
Cheng Chen

Reputation: 43531

It seems that Move is a reference type. So your variable plannedMove is null by default.

if (plannedMove == null)
{
   // do something
} 

If it's a value type, check Nullable<T>

Upvotes: 0

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29640

You test whether it's empty with:

if (plannedMove == null)

You set it to empty with:

plannedMove = null;

When you declare it with public Move plannedMove;, it's set to empty (null) by default.

Upvotes: 1

Kamyar
Kamyar

Reputation: 18797

set it to null in your constructor, or whenever you want it to have nothing:

this.plannedMove = null

then you can check it like:

if (this.plannedMove != null) ...

Upvotes: 0

Ian Mercer
Ian Mercer

Reputation: 39297

public Move plannedMove = null;

...    

if (plannedMove == null)
  plannedMove = ... // calculate new one

return plannedMove;

Upvotes: 1

brumScouse
brumScouse

Reputation: 3226

By default this instance wont be instantiated and will be null, therefore

if (plannedMove != null)
{
   // do something here
}

would be fine.

Upvotes: 1

Related Questions