Void * alternative in C #

I am making a class that calls a callback function, and I want it to pass some data in some cases, but this data may be different. In C ++, I would use void *, but in C # this is unsafe, and that means it can get GCed. Is there a way to pass an unknown data type in C #?

+3
source share
6 answers

You have two options:

Generics (which allows you to specify the type when calling the method ... and the object will be correctly entered in this method.)

// Definition:
public void MyMethod<T>(T myParameter)
{
    /* My Code */
}

// Call:
MyMethod<int>(999);

// Call:
MyMethod<bool>(false);

Or System.Object (this means that you will need to set the actual type of the object inside your method and execute it accordingly)

// Definition:
public void MyMethod(Object myParameter)
{
    /* My Code */
}

// Call:
MyMethod(999);

// Call:
MyMethod(false);
+8

You will pass it with the object . Unlike C ++, you can make a safe type in C #, whereas you cannot in C ++.

+1
source

I think you should use Object.

0
source

If you work in .net 4, you can also use a type dynamic.

0
source

All Articles