2

I have many classes with many properties like this:

public AnyClass[] car
{
     get
     {
          return this.anyClassField;
     }
     set
     {
          this.anyClassField= value;
     }
}

In every set{} accessor I need to set isEmptyFlag=true if value is null. So I thought may be it is possible to write static extension somehow to do that automatically or may be another solution?

maszynaz
  • 309
  • 4
  • 11

2 Answers2

2

You can create a generic extension method to check if an array is null or empty.

Given the following code:

public class Foo
{
    private anyClass[] anyClassField;

    public anyClass[] car
    {
        get
        {
            return this.anyClassField;
        }
        set
        {
            this.anyClassField = value;
        }
    } 
}

public class anyClass
{
    // add properties here ....
}

You can create an extension method like this:

public static class CollectionExtensions
{
    public static bool IsNullOrEmptyCollection<T>(this T[] collection)
    {
        if (collection == null)
            return true;

        return collection.Length == 0;
    }
}

Using the code (don't forget to include the namespace of the CollectionExtensions class):

var foo = new Foo();

// returns true
bool isEmpty = foo.car.IsNullOrEmptyCollection();

// add 1 element to the array....
foo.car = new [] { new anyClass() };

// returns false
isEmpty = foo.car.IsNullOrEmptyCollection();
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
0

Static extensions are coupled with a type. I don't know how your all classes are structures, but even if they all structured perfectly you will need add the code manually for every class in every property that has to behave like this.

This may be a solution. I would personally go for polymorphic solution: so declaring the base class virtual methods/properties that acts like I want and call them from the child class. Also because extensions are good for extending functionality of something what you are not able to do in other ways (not your library, the code that you not allowed to touch, 3rd part library...)

Another solution could be using of AOP (Aspect Oriented Programming), like form example:

Aspect Oriented Programing (AOP) solutions for C# (.Net) and their features

But there is a learning curve.

Community
  • 1
  • 1
Tigran
  • 61,654
  • 8
  • 86
  • 123