user1347198
user1347198

Reputation:

static property which returns class instance

I would like to use something similar as link! Part of the source code looks like that:

public struct Vector3
{
    public static Vector3 zero { get; }
}

This function returns an already initialized Vector (which 0 on every axis). Is this possible, because it is a struct? That's what I have:

public class WorldBlock
{
    public enum e_WorldBlockType
    {
        Undef,
        Earth,
        Stone,
        Air // no block set
    }

    public static WorldBlock Empty { get; }
    public e_WorldBlockType BlockType { get; set; }
    public bool IsWalkable { get; set; }

    public WorldBlock(e_WorldBlockType blockType = e_WorldBlockType.Undef, bool isWalkable = false)
    {
        this.BlockType = blockType;
        this.IsWalkable = isWalkable;
    }
}

But I get this: error CS0840: 'WorldBlock.Empty.get' must have a body because it is not marked abstract or extern. The property can be automatically implemented when you define both accessors

How should I write the body?

EDIT: If I add for example a private set, it compiles, but if I use it, I get a null pointer exception.

Upvotes: 1

Views: 826

Answers (4)

Håkan Edling
Håkan Edling

Reputation: 2753

If you only want an empty WorldBlock I suggest you write:

public static readonly WorldBlock Empty = new WorldBlock();

Instead of your Property. However it's kind of dodgy since the setters of the "Empty" object is public, so there's really no guarantee that it's actually empty.

Upvotes: 1

Ameen
Ameen

Reputation: 2586

Should your "Empty" instances be shared and be the same? If so, the following body is probably what you are looking for.

private static WorldBlock emptyInstance;
public static WorldBlock Empty
{
   get
   {
      if (emptyInstance == null)
      {
         //initialize it
      }
      return emptyInstance;
   }
}

Upvotes: 0

poy
poy

Reputation: 10507

You have to do:

public static WorldBlock Empty
{
  get{return someThing; }
}

Replace someThing with whatever you were wanting Empty to store.... If thats null or whatever.

From your title... it looks like you want to return an instance of the class. If you only ever want one instance of this class... you're looking for the Singleton design pattern.

Upvotes: 0

ichramm
ichramm

Reputation: 6642

Something like this:

private static WorldBlock __empty = ...;

public static WorldBlock Empty {
  get {
    return WorldBlock __empty;
  }
}

Upvotes: 0

Related Questions