psibot
psibot

Reputation: 679

How can I implement an extention property class for primitive Types in a clean way?

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?

Upvotes: 2

Views: 1288

Answers (3)

Adrian Zanescu
Adrian Zanescu

Reputation: 8008

For value types, this will not work. You'll need to reassign the new value to the variable. Eg:

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

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

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

You'll have to do this to string too even if they are reference type as they are immutable (there's no way to change a string in place without using unsafe pointer hacks)

Upvotes: 0

particle
particle

Reputation: 3350

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.

Upvotes: 4

ShdNx
ShdNx

Reputation: 3213

According to your question, you want to treat primitive types as reference types, which is not possible (only via the ref keyword). To make this clear, consider the following:

int DoSomething(int n)
{
    n = 5;
    return n;
}

int a = 3;
DoSomething(a); // a is still 3
a = DoSomething(a); // a is now 5

Therefore, this won't work as intended:

int oldValue = 1;
oldValue.Other(); // oldValue won't change

But this will:

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

Upvotes: 0

Related Questions