Returning a static array without using a class field

Posted by Bart Friederichs on Stack Overflow See other posts from Stack Overflow or by Bart Friederichs
Published on 2012-12-14T10:30:59Z Indexed on 2012/12/14 11:04 UTC
Read the original article Hit count: 211

Filed under:

I have the following base and derived (partial, for sake of brevity) classes:

class Base {
     public abstract int[] someArray { get; }
}

class Derived : Base {
     private readonly static int[] _someArray = new int[] { 1,2,3,4 };
     public override int[] someArray { 
         get {
              return _someArray;
         }
     }
}

What I would like now, is put the new int[] { 1,2,3,4 } in the return part of the getter. But, that would create a new array every time the getter is called.

Is it possible to directly return some kind of object, which stays the same for all objects of class Derived ?

Something along the lines of (I know this is invalid C#):

  get {
        return (int[]) { 1, 2, 3, 4 };
  }

© Stack Overflow or respective owner

Related posts about c#