I would like to make one method like this:
public void SomeMethod(int myInt,<float or double or MyClass> myFloatorDoubleorMyClass)
{
}
And not only with generics, but also with any class. I would like to avoid this:
public void SomeMethod(int myInt, float myFloat)
{
}
public void SomeMethod(int myInt, double myFloat)
{
}
public void SomeMethod(int myInt, MyClass myClass)
{
}
Is this feasible?
CodePudding user response:
You can use overloading like this:
public void SomeMethod(int myInt, double myDouble)
{
// ...
}
public void SomeMethod(int myInt, float myFloat)
{
SomeMethod(myInt, (double)myFloat);
}
Note that this is valid because a float
can be put into a double
without loosing precision.
Update: The question was updated, and specifically requests to avoid overloading. In this case my answer above is no longer relevant. I still believe (as others who commented on this post) that overloading in this case is prefered over the alternative (using generics).
BTW - In this specific case a float
can be automatically converted to a double
. But using overloading is a good solution also when you have types that do not convert automatically.
CodePudding user response:
You can achive this with Generics
Could look like
public void SomeMethod<T>(int myInt, T myFloatorDouble)
{
}
But it could be cleaner with overloads like
public void SomeMethod(int myInt, float myFloat)
{
}
public void SomeMethod(int myInt, double myDouble)
{
}
Depends on the logic in your method. If you have to cast inside the method, I would recommend overloads for example.