Pijusn
Pijusn

Reputation: 11293

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 that data may vary. In C++ I would use void* but in C# it's unsafe and it means it might get GCed. Is there any way of passing unknown type of data in C#?

Upvotes: 3

Views: 3272

Answers (6)

canon
canon

Reputation: 41675

You've got two options:

Generics (which allow you to specify the type when you call the method... and the object will be properly typed within the method.)

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

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

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

Or System.Object (which means you'll have to ascertain the object's actual type inside your method and cast appropriately)

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

// Call:
MyMethod(999);

// Call:
MyMethod(false);

Upvotes: 8

Oliver
Oliver

Reputation: 45101

If you're working in .net 4 you can also use the dynamic type.

Upvotes: 0

Sean
Sean

Reputation: 62472

You'd pass it around at an object. Unlike C++ you'll be able to do a type safe cast in C#, whereas you can't in C++.

Upvotes: 1

Joe
Joe

Reputation: 47609

You should use Generics for this.

http://msdn.microsoft.com/en-us/library/twcad0zb.aspx

Upvotes: 8

Adam Driscoll
Adam Driscoll

Reputation: 9483

The simplest solution would be to use the object type because all other objects inherit from this object. Doing so you allow yourself to pass in any object type.

http://msdn.microsoft.com/en-us/library/system.object.aspx

Upvotes: 1

james_bond
james_bond

Reputation: 6908

I think you should use Object.

Upvotes: 0

Related Questions