C# – How to implement an extention property class for primitive Types in a clean way

c

Basicly what I would like to is generate Other random values which have not the same value of the given value.

I somehow can not get hold of the primitive Types in a nice way.

The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single.

Here is basicly what I am trying to do.

  int oldValue = 1;
  oldValue.Other(); // 2

  long oldValue = 1;
  oldValue.Other(); // 2

  string oldValue = "1";
  oldValue.Other(); "5"

Has someone suggestions how I could tackle this nicely?

Best Answer

There is a base class called ValueType. The problem is that you need to cast the value to child when using it.

e.g

int a =3;
int b = (int)a.abc();

extension look like following

public static class ValueTypeExtension
{
    public static ValueType abc(this ValueType a) {

        return default(ValueType);
    }
}

you have to perform type check on parameter 'a' in if elseif to correctly return the value you intend to.

e.g

    if( a is Int32 )
      return 4;

Update: string is not exactly a value type but its treated like one. You still have to handle string in a seperate extension method.

Related Topic