In C++ I routinely use this templated function...
template<typename T>
bool isPowerOf2 (T x) // returns nonzero if x is a power-of-2
{
return x && ((x & (~x + 1)) == x);
}
...and I'm trying to implement the same thing in C#. So here's the best I can come up with:
public class Utils
{
// ...
public static bool isPowerOf2<T>(T x) // returns true if x is a power-of-2
{
return (x != 0) && ((x & (~x + 1)) == x);
}
}
But Visual Studio complains that error CS0019: Operator '!=' cannot be applied to operands of type 'T' and 'int' and error CS0023: Operator '~' cannot be applied to operand of type 'T'.
If I remove the generic stuff & just make it "public static bool isPowerOf2(int x)", it works fine (just like in various implementations here), but I'd like the implementation to be generic so it would work on any integer type.
This is a good illustration of why C# generics are not C++ templates. C# must be able to compile code without knowing T, while C++ could postpone compiling until the type of T is known. This lets C++ figure out how to perform ~, +, &, and so on.
The simplest approach with C# is to make multiple overloads for types that you plan to use with the function. This results in a small amount of code duplication, but it reads much better than other options, such as generating code dynamically with LINQ expressions.
If performance is not critical, you could also use Convert.ToInt64:
bool isPowerOf2 (object obj) {
var x = Convert.ToInt64(obj);
return x && ((x & (~x + 1)) == x);
}
C# does static type checking, this can be bypassed declaring dynamic type. You can still do what you want to do having input parameter is of type dynamic. Please note ~ works only on integers, fails for float and double.
public class Utils
{
// ...
public static bool isPowerOf2(dynamic x)
{
return (x != 0) && ((x & (~x + 1)) == x);
}
}
Check this example
Related
I'm trying to make some method like below.
It just add two given objects and return.
object add(object a, object b);
I already tried it with dynamic keyword. Unfortunately this one does not work on iOS. (the platform does not allow runtime code generations)
dynamic add(dynamic a, dynamic b) => a + b;
So, here's my second try and I realized that it's gonna be hell with this way.
private static HybInstance Add(HybInstance a, HybInstance b)
{
if (a.Is<Int32>()) return AddInt32(a, b);
/* and so on... */
}
private static HybInstance AddInt32(HybInstance a, HybInstance b)
{
Int32 ia = a.As<Int32>();
if (b.Is<Int16>()) return HybInstance.Int(ia + b.As<Int32>());
if (b.Is<Int32>()) return HybInstance.Int(ia + b.As<Int32>());
if (b.Is<Int64>()) return HybInstance.Int64(ia + b.As<Int64>());
if (b.Is<float>()) return HybInstance.Float(ia + b.As<float>());
throw new SemanticViolationException($"");
}
// the method should support custom operators too
private static MethodInfo GetAddMethod(HybInstance left) {
return left.GetMethods("op_Addition").FirstOrDefault();
}
Is there any smarter way to add two objects?
addition:
Here are some examples what I want to do.
Just add any kind of objects or throw exception if not possible.
add(1, 1); // 2
add(1, "b"); // exception
add("a", "b"); // "ab"
// and this one also should be work
add(some_class_with_operator_overloading, 10);
Closest you could get using standard .NET types is probably IConvertible:
static IConvertible Add (IConvertible a, IConvertible b)
{
if (a is string) return a.ToString() + b;
if (b is string) return a + b.ToString();
// other special cases here
return a.ToDouble(CultureInfo.CurrentCulture) + b.ToDouble(CultureInfo.CurrentCulture);
}
static void Main(string[] args)
{
IConvertible a = 1;
IConvertible b = 2;
IConvertible s = "string";
Console.WriteLine(Add(a, b));
Console.WriteLine(Add(s, s));
Console.WriteLine(Add(a, s));
}
Produces
3
stringstring
1string
It's impossible to add two objects, because there's nothing about objects that can be added.
It's like you would like add "something" to "something" and expected someone to answer your question with precise answer - it's impossible.
object don't have any fields or properties, so how you'd like to add them??
Unless you have in mind some kind of general rule of adding objects based on their real type, then it would become possible: you would have to check the type of input parameters and then in (rather) huge switch statement return appropriate result (eg. concatenation for strings, simple addition for integers...).
Did you try with generics, 2 things though:
You are wrapping different objects in same wrapper, seems like a design issue, but will leave it since I do not know more.
Most of the int can be directly changed to Int64 and then there will not be that many special cases
I would have a generic function, and would pass it the Add/Combine function which can be defined for different types. Seems to be a cleaner approach.
public T Add<T1, T2, T>(T1 firstObject, T2 secondObject, Func<T1,T2,T>Combine)
{
var result = Combine(firstObject, secondObject);
return result;
}
Update
Seems like this will not work either
Limitations of Xamarin.iOS
No Dynamic Code Generation
Since the iOS kernel prevents an application from generating code dynamically, Xamarin.iOS does not support any form of dynamic code generation. These include:
The System.Reflection.Emit is not available.
No support for System.Runtime.Remoting.
No support for creating types dynamically (no Type.GetType ("MyType`1")), although looking up existing types (Type.GetType ("System.String") for example, works just fine).
Reverse callbacks must be registered with the runtime at compile ti
However
Why does LambdaExpression.Compile() work on iOS (Xamarin)?
On platforms that support code generation, Reflection.Emit-based
LambdaCompiler
is used.
If that's not available, the expression is interpreted using the
interpreter
For example, there are classes that interpret Constant and Add.
Original
I am not sure how much mileage you could get out of this, but you could use expressions
public static object Add<T,T2>(T a,T2 b)
{
var paramA = Expression.Parameter(typeof(T), "a");
var paramB = Expression.Parameter(typeof(T2), "b");
var body = Expression.Add(Expression.Convert(paramA, paramB.Type), paramB);
var add = Expression.Lambda<Func<T, T2, T2>>(body, paramA, paramB).Compile();
return add(a, b);
}
The assumptions it that it will try to convert to the second parameter type and return of that type.
Obviously you any class will need the appropriate operators
Given
public struct Test
{
// user-defined conversion from Fraction to double
public static implicit operator int(Test f)
{
return 10;
}
public static implicit operator Test(int i)
{
return new Test();
}
// overload operator *
public static Test operator +(Test a, Test b)
{
return new Test();
}
}
Example
Console.WriteLine(Add(1, 2));
Console.WriteLine(Add(1, 2.0));
Console.WriteLine(Add(1, new Test()));
Refelction can be used to walk the properties of both objects, check for name equivalency and numeric data type, then amend property values in a totally generic way:
public static void AddObjects(object oFrom, object oTo)
{
if (oFrom != null && oTo != null)
{
foreach (System.Reflection.PropertyInfo f in oFrom.GetType().GetProperties())
{
if ((oTo).GetType().GetProperty(f.Name) != null)
{
try
{
string sType = f.GetType().ToString().ToLower();
if (sType==("int") )
{
oFrom.GetType().GetProperty(f.Name).SetValue(oFrom, (int)(f.GetValue(oFrom)) + (int)(f.GetValue(oTo)));
}
if (sType=="int32" )
{
oFrom.GetType().GetProperty(f.Name).SetValue(oFrom, (Int32)(f.GetValue(oFrom)) + (Int32)(f.GetValue(oTo)));
}
if (sType==("int64") )
{
oFrom.GetType().GetProperty(f.Name).SetValue(oFrom, (Int64)(f.GetValue(oFrom)) + (Int64)(f.GetValue(oTo)));
}
// keep adding for all numeirc types. maybe theres a better way?
}
catch (Exception ex)
{ }
}
}
}
}
In C# I sometimes have to do something if the object is of some type.
e.g.,
if (x is A)
{
// do stuff but have to cast using (x as A)
}
What would be really nice if inside the if block, we could just use x as if it were an A, since it can't be anything else!
e.g.,
if (x is A)
{
(x as A).foo(); // redundant and verbose
x.foo(); // A contains a method called foo
}
Is the compiler just not smart enough to know this or is there any possible tricks to get similar behavior
Can the Dlang effectively do something similar?
BTW, I'm not looking for dynamic. Just trying to write less verbose code. Obviously I can do var y = x as A; and use y instead of X.
In D, the pattern you'd usually do is:
if(auto a = cast(A) your_obj) {
// use a in here, it is now of type A
// and will correctly check the class type
}
For one statement (or chain-able calls) you can use (x as A)?.Foo() in C# 6.0+ as shown in Is there an "opposite" to the null coalescing operator? (…in any language?).
There is no multiple statements version in the C# language, so if you want you'll need to write your own. I.e. using Action for body of the if statement:
void IfIsType<T>(object x, Action<T> action)
{
if (x is T)
action((T)x);
}
object s = "aaa";
IfIsType<string>(s, x => Console.WriteLine(x.IndexOf("a")));
I believe this is a feature is under consideration for C# 7. See the Roslyn issue for documentation, specifically 5.1 Type Pattern:
The type pattern is useful for performing runtime type tests of reference types, and replaces the idiom
var v = expr as Type;
if (v != null) { // code using v }
With the slightly more concise
if (expr is Type v) { // code using v }`
As for Dlang, I would reference their if statement syntax documentation here.
If there are operator overloads for <, > and ==, shouldn't the compiler be able to create for <= and >= automatically?
(a <= b) means (a < b || or a == b)
(a >= b) means (a > b || or a == b)
At least, the compiler does the same for += if + is overloaded.
+= and >= are not the same from functional point of view.
u+=2 is a short hand operand over u=u+2
>= is short hand for > || ==.
So you have 2 consecutive calls in second case MoreThan() || Equal(), which may provide problems like
short circuits
stack overflow
return type of that functons may not be bool at all (as mantioned by #vcjones)
...
But in general: aggregate automaticaly (under the hood) user defined functions is never a good idea as a final result is not stable, as depends on concrete implementation, so unpredictable. And you don't want your compiler to generate unpredictable code.
No, it cannot. One reason being that operators don't have to return a bool (though I don't know why anyone would do this). For example:
public static string operator <(Class1 a, Class1 b)
{
return "hello";
}
public static int operator >(Class1 a, Class1 b)
{
return "bye";
}
This compiles fine, and in this scenario the compiler can't really make the other operator automatically. How should the compiler decide what the opposite value of a string is?
I would like to create a generic method which performs basic mathematical operations. For eg. If a double is passed to the function, it will return double.
public static T Multiply<T> (T A, int B)
{
//some calculation here
return (T) A * B;
}
This doesn't work for me.
EDIT: I get an error Operator '*' cannot be applied to operands of type 'T' and 'int'
However I am wondering if there are other ways to achieve what I am trying to?
Thanks
You can do it by constructing and compiling a LINQ expression for the specific type, like this:
private static IDictionary<Type,object> MultByType = new Dictionary<Type,object>();
public static T Multiply<T>(T a, int b) {
Func<T,int,T> mult;
object tmp;
if (!MultByType.TryGetValue(typeof (T), out tmp)) {
var lhs = Expression.Parameter(typeof(T));
var rhs = Expression.Parameter(typeof(int));
mult = (Func<T,int,T>) Expression.Lambda(
Expression.Multiply(lhs, Expression.Convert(rhs, typeof(T)))
, lhs
, rhs
).Compile();
MultByType.Add(typeof(T), mult);
} else {
mult = (Func<T,int,T>)tmp;
}
return mult(a, b);
}
To avoid recompiling the expression each time it is used, one could cache it in a dictionary.
Note that this approach has certain limitations:
Multiplication of T by T is expected to be defined,
The output of multiplication is expected to be T without conversion. This is not true for types smaller than int,
The type must support conversion from int.
None of this is checked at compile time.
This is the simplest to implement, but is not efficient:
public static T Multiply<T>(T A, int B)
{
T val = default(T);
try
{
val = (dynamic)A * B;
}
catch
{ }
return val;
}
Depending on your needs it might be fine for you. You may consider not handling the exception in the method, or using an out value so that you can return both the answer and a success value.
Being stuck on an on older .Net version, without access to dynamic, I have a very simple class that does very much what you're looking for, and allows for use of actual operators: Numeric It may be worth a look on current .Net as well.
Method declaration:
public static T LerpMinMax<T>(Numeric<T> input, Numeric<T> inputMin, Numeric<T> inputMax, Numeric<T> outputMin, Numeric<T> outputMax)
{
if (input <= inputMin)
{
return outputMin;
}
else if (input >= inputMax)
{
return outputMax;
}
return outputMin + ((input - inputMin) / (inputMax - inputMin)) * (outputMax - outputMin);
}
And then use:
float lerp = LerpMinMax<float>(0.55f, 0.0f, 0.1f, 0.0f, 1000.0f);
It's definitely not as flexible as MiscUtil's Operator, but was intended to be simple and (relatively) fast. It's still significantly slower than using operations directly (say by using T4 templates that spit out non-generic type-specific implementations) but used in the above way it's equivalent to MiscUtil's Operator class. It also obviously has the benefit of generally more readable algorithm implementations, and can support custom classes that implement operators.
You should add Dynamic in front of the A
and the conversion to T must be done on the full calculation
public static T Multiply<T>(T A, int B)
{
return (T)((dynamic)A * B);
}
Here's my example for using generics to compare to numbers:
public bool TIsEqual<T>(T f1, T f2, T margin)
{
T diff = default(T);
T error = default(T);
diff = Math.Abs((dynamic)f1 - f2);
error = (dynamic)margin * f1;
return (dynamic) diff < error;
}
Why can not I run the following code ?
static int num = 0;
static void Main(string[] args)
{
(num == 0) ? inc() : dec();
}
public static void inc()
{
num++;
}
public static void dec()
{
num--;
}
Why doesn't C# allow me to use the ternary "?:" operator to check a condition and then run a method accordingly without the need to return any value? Equivalently to this:
if (num == 0) inc();
else dec();
I am not sure if the same rule is applied in other languages, e.g., Java, C++, etc...
why can not I run the following code ?
Because you're trying to violate the language specification. The operands of the conditional operator (section 7.14 in the C# 4 spec) have to be expressions - and an invocation of a method with a return type of void is explicitly "only valid in the context of a statement-expression" (see section 7.1 of the C# 4 spec).
The purpose of the conditional operator is to provide an expression which is the result of evaluating one of two expressions based on a condition. It's not to execute one of two actions based on a condition. Just use an if statement.
Likewise the conditional operator does not form a valid statement on its own, any more than various other operators do:
a + b; // Invalid
x = a + b; // Valid, assignment expression can be an expression-statement
Explicitly from section 8.6 of the spec:
Not all expressions are permitted as statements. In particular, expressions such as x + y and x == 1 that merely compute a value (which will be discarded) are not permitted as statements.
Jon Skeet's answer is perfectly documenting that C# intentionally went a different route than C++. It is difficult to say why, but I will try because I believe that that question deserves an answer, too.
C# shares a lot of syntax with C++ and with Java. In this case, the Java way was chosen. This concerns both the inability to write 2 + 2; as a standalone statement, as well as requiring that ternary operator returns a value.
I believe that both of these decisions have a lot to do with elimination of inaccessible code. The + operator in 2 + 2 can be optimized away and therefore if it serves any purpose in the code, that purpose is unreliably served! Static analysis (compilation error or warning) should ideally tell you that there seems to be a semantic problem in such a case and force you to delete or rewrite the inaccessible code.
So, expressions are no longer always statements, and the C grammar needs to be redefined for Java/C#, with expressions always returning values and statements never returning values.
Now ?: and if-else differ primarily in one being an expression and one being a statement, at least in their typical uses. So the redefined grammar simply chose to ban void ternaries and recommend if-else for that purpose.
Because Ternary operator assigns value based on a boolean expression. Its basic C# spec. If your methods are void return type then best is to use if - else or switch case.
int a = true ? 0 : 1; //Always works
true ? 0 : 1; //This will never work.
Or you example modified a little.
static int num = 0;
static void Main(string[] args)
{
num = (num == 0) ? inc(num) : dec(num);
}
public static int inc(int lnum)
{
return lnum + 1;
}
public static int dec(int lnum)
{
return lnum - 1;
}
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.
It does not act the way you have described in your question.
Here are more bytes on the ternary operator
http://msdn.microsoft.com/en-us/library/ty67wk28%28v=vs.80%29.aspx
But it will work when used this way:
static int num = 0;
static void Main(string[] args)
{
num = (num == 0) ? inc(num) : dec(num);
}
public static int inc(int number)
{
return number + 1;
}
public static int dec(int number)
{
return number - 1;
}