Code
Class
using System;
using System.Collections.Generic;
// In case you really, really want to know,
// this class is called Ticket in my real code and it's used as a Tambola ticket.
public class Foo
{
public int?[,] Value { get; private set; } = new int?[3 , 9]
public Foo () => Value = InternalGenerate()
public static Foo Generate () => new() { Value = InternalGenerate() };
protected static int?[,] InternalGenerate ()
{
// Generate a random instance of this class.
}
}
Usage
class Program
{
static void Main ()
{
Bar( new() );
}
static void Bar ( Foo foo )
{
int width = foo.GetLength(1);
int height = foo.GetLength(0);
int?[] array = foo.Cast<int?>().ToArray(); // convert foo to 1d array.
// get "corners" of foo
int tl = (int) array.First(e => e.HasValue);
int fl = (int) array.Take(width).Last(e => e.HasValue);
int lf = (int) array.Skip(( height - 1 ) * width).First(e => e.HasValue);
int ll = (int) array.Last(e => e.HasValue);
// this code comes from
// stackoverflow.com/questions/68661235/get-corners-of-a-2d-array
}
}
This code will fail.
Question
I have a class called Foo
.
It's actual value should be a 2d array of type int?
- however, when I try to use an instance of Foo as a int?[,]
(look at Usage section of code), it fails (which is expected).
So, how do I make it possible to use an instance of Foo
as if it is a collection, instead of having to use {instance of Foo}.Value
?
I'm not sure, but I believe this is called a wrapper.
What I've tried
I tried to inherit Foo
from IEnumerable
- but I've never created a custom collection type before. So, after hours of reading tutorials and staring at C#'s source code, I finally resorted to asking a question here, on stack overflow.
BUT, as I said, I wasn't able to implement IEnumerable
- doing that may still be the answer to my question. In that case, please tell me how to do so.
This is probably my longest question yet
>`
– Mikal Schacht Jensen Aug 09 '21 at 07:33