"The following code is not executing properly, try to figure out why."
public class CustomMath {
public static int multiply(int a, string b) {
return a * b;
}
}
Here's my solution:
public class CustomMath
{
Int i = 1;
public static int multiply(int a, int b)
{
return a * b;
}
}
I'm still plugging away at it started looking at operator overloading. Still catching the fail so I guess I am still not seeing it or failing to understand something about using operator overloading. Is the operator overloading my only issue or is my return syntax off?
using system;
public class CustomMath
{
public static int operator *(int a, string b)
{
return a * b;
}
}
So I'm looking into binary operators, pretty sure my issue is that I am not expressing the int and string properly.
from the error that you've got you should understand that the function signiture is wrong and you need to change the type of b (string) to be int. so your code would be:
public class CustomMath
{
public static int multiply(int a, int b)
{
return a * b;
}
}
Your operator overload won't work, because in order to overload the multiplication operator, at least one of the operands has to be of a user-defined type.
The thing is, you don't need overloading at all. There are methods in the .NET framework designed specifically to "extract" an integer from a string, which is what you should do before multiplying anything. There are two easy ways of achieving this: int.Parse and int.TryParse. Just take a look at the MSDN documentation to figure out how they work and choose the best in your specific scenario.
And here is int.Parse in action:
string s = "5";
int i = int.Parse(s);
int j = i + 10 // At this point j = 15
Related
I didn't get any errors. I'm just wondering. Why it doesn't work when I typed "no4.Print();". did not class already create?
I was learning operator overloading. i noticed that it only works when i use Console.WriteLine func. If i tried to use Print function inside the class it errors.
using System;
class Number{
private int myNumber;
public Number(int myNumber){
this.myNumber=myNumber;
}
public static Number operator *(Number a, Number b){
return new Number(a.myNumber*b.myNumber);
}
public void Print(){
Console.WriteLine(this.myNumber);
}
public static implicit operator int(Number a) {
return a.myNumber;
}
public static implicit operator Number(int a) {
return new Number(a);
}
}
class HelloWorld {
static void Main() {
Number no1 = new Number(5);
Number no2 = new Number(2);
Number no3 = no1*no2;
no3.Print();
int no4 = new Number(1312);
Console.WriteLine(no4); //It doesnt work no4.Print();
Number no5 = 2121;
no5.Print();
}
}
You can't call no4.Print(); because the int type/class does not have such a method. Also, nobody is telling the variable to get converted to a Number object. However, when you write something like
((Number)no4).Print();
you are explicitly converting your int value to a Number object with the help of your defined implicit operator Number(int a) operator.
I'm very fresh to C#
Currently learning Operator overloading
i'm trying to do something like this:
string val = 500; (I can't implicitly)
and then
Number n1 = val;
I manages to get the Number n1 = someintvalue, for instance:
Number n1 = 500;
like this:
public struct Number
{
public int Value { get; set; }
public Number(int Val)
{
Value = Val;
}
public static implicit operator Number(int num)
{
return new Number(num);
}
}
However, when trying to make Number n1 = val; (when val is a string)
I simply cant since the first line cant compile:
string val = 500;
and the following wont work:
public static implicit operator string(int A)
{
return new string(A);
}
because of 1 error which i can not understand
1)User-defined conversion must convert to or from the enclosing type
by the way i get the idea of op overload
underthis specific case of: return new Number(num);
I simply init the ctor
still need some more fundemental understanding
thx ahead!
I presume the function you quote is within the Number class. You have added a conversion operator from an int to a string within that class, which is not legal. You can only add operators that convert to or from the type they're defined in, such as:
public static implicit operator string(Number A)
{
return new string(A.Value);
}
which will fail because string does not have a constructor that takes an int. You could do:
public static implicit operator string(Number A)
{
return A.ToString();
}
But the standard way to "convert" to a string is to overload the ToString method, which the compiler often calls automatically when a conversion to string is requested:
public override string ToString()
{
return Value.ToString();
}
class MyNumber
{
public int Number { get; set; }
}
I don't understood why the below code will throw error.
class Program
{
public static void Main()
{
MyNumber firstNumber = new MyNumber();
MyNumber secondNumber = new MyNumber();
firstNumber.Number = 10;
secondNumber.Number = 5;
MyNumber sum = firstNumber + secondNumber;
}
}
Currently there is no + operator defined for MyNumber this means that you get a syntax error when you try to use it, instead you probably want something like this:
class MyNumber
{
public int Number { get; set; }
public static MyNumber operator +(MyNumber c1, MyNumber c2)
{
//sum the .Number components and return them as a new MyNumber
return new MyNumber{ Number = c1.Number + c2.Number };
}
}
What this does is explain what + means in the context of your MyNumber class
Each of these addition operators yields different results based on the type it is used against.
string s = "Foo" + "Bar"; //Resulting in FooBar
int i = 1 + 3; //Resulting in 4
Now for your custom class, how do you expect the operator to function if you dont tell it what to do?
The answer is really simple the compiler does not know how to handle those operation for your custom type.
The example quoted by you is simple, and you want, when I say add + then add the properties with the same name but lets take another example Multiplication* for a basic Complex number class you have already studied and we know multiplication for Complex number class is,
(a + i b) * (c + i d) = ac -bd + i (bc + ad)
do you think so compiler has a magic trick and he knows this is complex number class and multiplication is to be carried like this, Surely it does not know for that you need to tell it this way you have to carry out operation, that's why operator overloading is needed and of course if you don't overload you get exception in Error list stating
Error 1 Operator '+' cannot be applied to operands of type 'ConsoleApplicationTest.Class1' and 'ConsoleApplicationTest.Class1'
So for complex class implementation will be like this,
public class Complex
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public static Complex operator *(Complex c1, Complex c2)
{
return new Complex(c1.real * c2.real - c1.imaginary * c2.imaginary, c1.imaginary * c2.real + c1.real * c2.imaginary);
}
}
My brain has turned to jelly, or I'm having an out of mind experience, or something. I'm tinkering with a class hierarchy that looks a bit like this:
My Money class looks like this:
public abstract class Money
{
public int Amount { get; set; }
public static bool operator ==(Money leftSide, Money rightSide)
{
// Money can only be equal if it is in the same currency.
if (leftSide.GetType() != rightSide.GetType()) return false;
return leftSide.Amount == rightSide.Amount;
}
public static bool operator !=(Money leftSide, Money rightSide)
{
// If the currencies are different, the amounts are always considered unequal.
if (leftSide.GetType() != rightSide.GetType()) return true;
return leftSide.Amount != rightSide.Amount;
}
public static Money operator *(Money multiplicand, int multiplier)
{
var result = multiplicand * multiplier;
return result;
}
public static Dollar Dollar(int amount)
{
return new Dollar(amount);
}
public static Franc Franc(int amount)
{
return new Franc(amount);
}
}
My Dollar operator * looks like this:
public static Dollar operator *(Dollar multiplicand, int multiplier)
{
var result = multiplicand.Amount * multiplier;
return new Dollar(result);
}
Now, if I run this test code, I get a Stack overflow (wahoo!)
{
Money fiveDollars = Money.Dollar(5);
Money timesTwo = fiveDollars*2;
}
I had expected that this would recursively call the subclass (Dollar) operator *, which would return a definite result since (Dollar * int) is defined non-recursively. Since this doesn't work, the alternative is that I have done something dumb. Why doesn't this work? What would be the right way to get this behaviour?
You seem to have left out .Amount
public static Money operator *(Money multiplicand, int multiplier)
{
var result = multiplicand.Amount * multiplier;
return result;
}
The problem is that you expect that you can override operators in derived classes and expect dynamic binding. This is not the way it works in C#. Operators are overloaded and the actual overload is chosen compile-time. This means that the following code is recursive and calls itself:
public static Money operator *(Money multiplicand, int multiplier)
{
var result = multiplicand * multiplier;
return result;
}
Another example where you can see the difference between operator overloading and method overriding is this:
int a = 5;
int b = 5;
Console.WriteLine(a == b); // true
Console.WriteLine(a.Equals(b)); // true
Console.WriteLine((object)a == (object)b); // false
Console.WriteLine(((object)a).Equals((object)b)); // true
In the third case, C# treats a and b as objects instead of integers, so it uses the default == operator that is used for objects: comparing references (in this case the references of boxed integers).
This can make it awkward to define operators on a class hierarchy where you want to redefine the operators in derived classes. It is especially awkward when the behavior depends on the combination of both operands, since C# (and most other OOP languages) lacks support for multiple dispatch. You can solve this by using the visitor pattern, but I think in this case you should reconsider if using subclasses for each currency is the best solution.
I have a simple scenario that may or may not be possible. I have a class that contains an integer, for this purpose I'll make it as simple as possible:
public class Number
{
public int Value {get; set;}
public string Name {get; set;}
}
public static void Print(int print)
{
Console.WriteLine(print);
}
public static string Test()
{
Number num = new Number (9, "Nine");
Print(num); //num "overloads" by passing its integer Value to Print.
}
// Result
// 9
How do I make the Test() function work as I have coded it? Is this even possible? I think this can be done with the explicit/implicit operator but I can't figure it out.
Try something like this
public static implicit operator int(Number num)
{
return num.Value;
}
class Number
{
public static implicit operator int(Number n)
{
return n.Value;
}
}
Implicit conversion
// Implicit conversion. num long can
// hold any value an int can hold, and more!
int num = 2147483647;
long bigNum = num;
Explicit Conversion
class Test
{
static void Main()
{
double x = 1234.7;
int a;
// Cast double to int.
a = (int)x;
System.Console.WriteLine(a);
}
}
Hope this may help you.
Implicit type conversion: Implicit type conversion takes place between smaller to larger integral types but not vice-versa or between derived class and base class. Conversion takes place in type safe manner by C# and no data loss takes place.
For example,
int a = 10;
long b = a;
float f = a;
Explicit type conversion: Explicit type conversion done by using built-in C# functions. Data may be lost while explicit type conversion, means if we convert double to int then precision may be lost. Explicit type conversion require casting. To do a casting, need to specify the type that you are casting to in front of the value or variable to be converted.
For example,
double d = 10.20;
int a = (int)d;
//Output: 10
To understand in details follow C# Basics - C# Type Conversion