'c# two parameters in one parameter in a method
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?
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
public static void SomeMethod(int myInt, object value)
{
if (value == null) { throw new Exception("exception"); }
else
{
var typecode = Convert.GetTypeCode(value);
if (typecode == TypeCode.Object && value.GetType().IsClass && value.GetType().Name == nameof(MyClass)) { var result = (MyClass)value; }
else if (typecode == TypeCode.Double) { var result = Convert.ToDouble(value); }
else if (typecode == TypeCode.Single) { var result = Convert.ToSingle(value); }
else { throw new NotImplementedException("exception"); }
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Mighty Badaboom |
Solution 3 | UÄŸur Demirel |