-2

I need an array with custom methods.

MyObject[] myObject = {myA, myB, myC};
myObject.myMethod(); // do my stuff

1. Is that possible?

2. How would myMethod be able to internally access myA, myB, and myC?

-

PS: Sorry to deceive all the down voting c# wizards, here. But I'm just starting with the language and I don't know about "Enumerations" of the referred question . So I did made a simpler straighter question with the hope of helping the ones of my kind.

Community
  • 1
  • 1
Alvaro Lourenço
  • 1,321
  • 1
  • 10
  • 21

2 Answers2

4

Q: Is that possible?

A: Yes, but you cannot inherit from Array. A different mechanism will help you, though.

Q: How would myMethod be able to internally access myA, myB, and myC?

A: You can use Extension Methods approach, as shown below:

static class Extension
{
    public static string Extend(this Array array)
    {
        return "Yes, you can";
    }
}

class Program
{

    static void Main(string[] args)
    {
        int[,,,] multiDimArray = new int[10,10,10,10];
        Console.WriteLine(multiDimArray.Extend());
    }
}
Dmitri Nesteruk
  • 23,067
  • 22
  • 97
  • 166
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
2

You can write Extension methods, see here

namespace ExtensionMethods
    {
        public static class MyExtensions
        {
            public static void myMethod(this MyObject[] items)
            {
                foreach(var item in items)
                {
                   //do something;
                }
            }
        }   
    }
Yahya
  • 3,386
  • 3
  • 22
  • 40