Povilas Dirse
Povilas Dirse

Reputation: 147

C# How to create your own data structure methods

I've been trying to google one interesting fact for me, but can't grab the terminology to fully understand this concept. For example, I create my own container which holds an array of Cars. For this specific array I want to implement "Place" method which inserts a given car in a specific order (place method has logic). And what I don't get is how it gets the job done. Here is the code:

   public static void Main(string[] args)
   {
      Car[] result = new Car[entries];
      result.Place(poppedValue);
   }
    public static class Extension
    {
        public static void Place(this Car[] array, Car car)
        {
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] != null)
                {
                    if (array[i].Year > car.Year)
                    {

                    }
                }
            }
        }
    }
    public class Car
    {
        public string Name;
        public int Year;
        public double MPG;

        public Car(string name, int year, double mpg)
        {
            this.Name = name;
            this.Year = year;
            this.MPG = mpg;
        }

        public bool ComplexMaths()
        {
            return (Year * MPG) % 2 == 0;
        }
    }

What I don't get is that in "Place" method, first argument is "this Car[] array" and when calling the method "Place" you don't give that argument. C# understands it by using result.Place... It's so confusing. Maybe someone can say what happends under the hood and how this "function" of C# is called. I would like to read about it more. Thank you.

Upvotes: 0

Views: 1110

Answers (1)

user12031933
user12031933

Reputation:

An extension method is a syntactic sugar that allows functionality to be added to existing classes even if sealed and without inheriting them.

This is also called a Trait.

In C# we use the keyword this for the first parameter to indicate that the static method, that must be in a static class generally called a Helper class, applies to the specified type.

For example:

public static class CarArrayHelper
{
    public static void Place(this Car[] array, Car car)
    {
    }
}

Indicates that we can apply the Place method on all arrays of Car.

Hence we can write:

var myArray = new Car[10];

myArray.Place(new car());

This is exactly the same as:

CarArrayHelper.Place(myArray, new car());

The Car class does not implement Place, so we added the functionality without changing the Car class or creating a subclass.

Here are some tutorials:

C# - Extension Method (TutorialsTeacher)

Extension Methods in C# (C-SharpCorner)

Extension Method in C# (GeeksForGeeks).

Upvotes: 2

Related Questions