Reputation: 11293
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
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
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
Reputation: 47609
You should use Generics for this.
http://msdn.microsoft.com/en-us/library/twcad0zb.aspx
Upvotes: 8
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