whats wrong with my code + a question about .this keyword

  • (2 Pages)
  • +
  • 1
  • 2

22 Replies - 976 Views - Last Post: 17 July 2010 - 01:47 PM Rate Topic: -----

#1 lookitstom  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 28
  • Joined: 12-July 10

whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 08:34 AM

hi again guys!
2 questions, first one is about a program that i'm trying to execute which won't work, and the second is about the .this keyword.

first question is from my c# book, which provided the following task. i have the idea & pretty sure i know how to write it, but a problem occurred.

this is the task :
Write a program with a Math class that has four methods - add, subtract, multiply and divide, each of which take 2 parameters. Call each method from Main() and provide an appropriate output statement to demonstrate that each method works. You don't need to have the user provide input; just provide the two integers to the methods within main.

this is my code :
namespace MathExercise
{
    public class Math

    {
        // private variables set here
        private int x;
        private int y;
        private int sum;
    
        public void doAdd() // Add method
        {
           
            sum = x + y;
            Console.WriteLine("sum of {0} + {1} = {2}",
                                x, y, sum);
        }

        public void doSubtract() // Subtract method
        {
            sum = x - y;
            Console.WriteLine("{0} - {1} = {2} ",
                               x, y, sum);
        }

        public void doMultiply() // Multiply method
        {
            sum = x * y;
            Console.WriteLine("(0} * {1} = {2} ",
                               x, y, sum);
        }

        public void doDivide() // Divide method
        {
            sum = x / y;
            Console.WriteLine("(0} / {1} = {2} ",
                               x, y, sum);
        }

        public Math(int myX, int myY) // constructor method
        {
            myX = x;
            myY = y;
        }
    }

    public class Tester
    {
        static void Main()
        {
            Math Add = new Math(6, 3);
            Add.doAdd(); // invoke the doAdd method

            Math Subtract = new Math(6, 3);
            Subtract.doSubtract(); //invoke the doSubtract method

            Math Multiply = new Math(6, 3);
           Multiply.doMultiply(); //invoke the doMultiply method

            Math Divide = new Math(6, 3);
            Divide.doDivide(); //invoke the doDivide method
        }

    }
}




these are the errors that the compiler tells me about :
Warning 1 Field 'StaticTester.Math.x' is never assigned to, and will always have its default value 0
Warning 2 Field 'StaticTester.Math.y' is never assigned to, and will always have its default value 0

can you guys explain what am i doing wrong?
i've announced the x and y variables at the beginning of the first class, and used a constructor method to convert the private int x and y into myX and myY that will be used later on in the main method. then, the variables were given a value at the main method, while creating a new instance of Math. what am i doing wrong?

the book gives a solution to the exercise, i wont copy it (unless you guys want me to), but i can tell you that what they did was while creating a method they gave it parameters within the parentheses [ example - public int Add( int left, int right) { return left + right; } ] etc. and at the main method in a new class they wrote -
Math m = new Math();
int sum = m.Add(3,5); and so on, then wrote it on the screen with a simple console.writeline.

so here are my questions -
a. why am i getting those errors?
b. was my solution to the exercise basically wrong? was the whole idea fked up?
c. i know that semantically using sum for divide etc. is wrong but thats the identifier that i thought of while writing the code. Syntax wise; is it wrong to give sum the value x + y at the beginning and then x - y and so on?


my second question is about the .this keyword.
the book gave the following example-
private int length;
// bits of code
public void SomeMethod (int length)
{
this.length = length;
}


what i cant seem to understand is the use of it. why should the compiler care that this.length refers to the member variable and length refers to the parameter? can't he understand that by himself? why should i use it and when?

any sort of help would be really appreciated! :)

Is This A Good Question/Topic? 0
  • +

Replies To: whats wrong with my code + a question about .this keyword

#2 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1251
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 08:50 AM

a. why am i getting those errors?
You're receiving those errors because your code in your Math.cs class is using the int variables x and y before you assign values to it.

So even though are are assigning them values via the constructor, your compiler doesn't know that! It cannot predict the future.

If you want to solve this problem quickly, just assign a default value when declaring the int variables.

b. was my solution to the exercise basically wrong? was the whole idea fked up?
Your idea is not wrong, but I would do something like this:

public class Math
{
    public int Add(int a, int B)/>
    {
        return a + b;
    }
   
    //Do the same for Subtract, Multiply and Divide.
}

//And using it in main:
Math mathClass = new Math();
Console.WriteLine(mathClass.Add(2,2).ToString()); //Output: 4
Console.WriteLine(mathClass.Add(2,5).ToString()); //Output: 7
Console.WriteLine(mathClass.Add(10,20).ToString()); //Output: 30



What advantages does this approach have?

Well by doing things this way you are decoupling the methods. Now you can use the returned value of your math and display it any you want with little change to your original code. If you use your previous code, you are limited to Console.WriteLine(), but this way you can capture that int result and show it anywhere.

c. i know that semantically using sum for divide etc. is wrong but thats the identifier that i thought of while writing the code. Syntax wise; is it wrong to give sum the value x + y at the beginning and then x - y and so on?
I don't understand your question so well. Are you asking if using sum as a keyword for all three arithmetic methods is wrong? No, but so you don't confused yourself why don't you rename it result?

Hope this helps.

This post has been edited by stapia.gutierrez: 17 July 2010 - 08:54 AM

Was This Post Helpful? 1
  • +
  • -

#3 lookitstom  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 28
  • Joined: 12-July 10

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 08:56 AM

hey stapia.gutierrez, thanks for your reply :)
first of all your solution was pretty much like the one the book gave, so yeah i understand why that one was better

a couple of questions -
a. alright i understand why the errors have occurred, what should i have done to make it work? i'm asking out of curiosity cause it annoys me that my solution didn't work :(
b. my third question was asking about what i did with the int sum. im not talking about the name i gave the identifier, i'm talking about my actions -
is it correct to give sum this value - "x + y" at the beginning of the code, and after a couple of bits of code change it to sum = x - y? no problem with that right?
c. still looking for an answer to the .this question.


edit -
just saw what you said about assigning values to the variable at the beginning - i know i could have done that, but thats not what they were looking for i guess ^.^ the whole point of the task was being able to give the values at main method i guess

This post has been edited by lookitstom: 17 July 2010 - 08:59 AM

Was This Post Helpful? 0
  • +
  • -

#4 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1251
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 09:03 AM

a. alright i understand why the errors have occurred, what should i have done to make it work?
Just assign a default value when declaring the x and y variables in your Math class. :)
int x, y = 0;



b. is it correct to give sum this value - "x + y" at the beginning of the code, and after a couple of bits of code change it to sum = x - y? no problem with that right?
Oh now I understand, of course not! You are after all using variables, there is absolutely no problem with using the same variables and acting differently with them.

c. still looking for an answer to the .this question.
I might be wrong on this one, but in over 5 years of programming I've seldom had a use for the this keyword. Someone will give you a more precise answer to this question.

This post has been edited by stapia.gutierrez: 17 July 2010 - 09:05 AM

Was This Post Helpful? 1
  • +
  • -

#5 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1634
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 09:08 AM

The this keyword is a reference to the current instance of the class you're working in. Remember, static classes cannot have a this pointer. The this keyword can be used to access members from within constructors, instance methods, and instance accessors.
Was This Post Helpful? 1
  • +
  • -

#6 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1251
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 09:13 AM

Psycho what is the difference between:

public class Person
{
    public string Name { get; set; }

    public Person(string name)
    {
        this.Name = name;
    }
}



public class Person
{
    public string Name { get; set; }

    public Person(string name)
    {
        Name = name;
    }
}



Don't they both do the exact same thing?
Was This Post Helpful? 0
  • +
  • -

#7 lookitstom  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 28
  • Joined: 12-July 10

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 09:14 AM

View Poststapia.gutierrez, on 17 July 2010 - 08:03 AM, said:

a. alright i understand why the errors have occurred, what should i have done to make it work?
Just assign a default value when declaring the x and y variables in your Math class. :)
int x, y = 0;



b. is it correct to give sum this value - "x + y" at the beginning of the code, and after a couple of bits of code change it to sum = x - y? no problem with that right?
Oh now I understand, of course not! You are after all using variables, there is absolutely no problem with using the same variables and acting differently with them.

c. still looking for an answer to the .this question.
I might be wrong on this one, but in over 5 years of programming I've seldom had a use for the this keyword. Someone will give you a more precise answer to this question.


thanks again for you help
about your first answer, i just thought of doing that, tried it out and when i execute i get the following -
console writes -
sum of 0 + 0 = 0
0 - 0 = 0

and then it crashes, giving me this error message with options to send an error report...


PsychoCoder, is this a keyword that is never used like stapia suggested?
Was This Post Helpful? 0
  • +
  • -

#8 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1251
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 09:16 AM

What error message are you getting? That doesn't make sense because in your code you give x and y values in the constructor. So you be using it like this: Math mathClass = new Math(2,2)

If you use it like this Math mathClass = new Math();, you'll obviously use the default constructor which does nothing to x and y, thus giving you 0 and 0.
Was This Post Helpful? 0
  • +
  • -

#9 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1634
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 09:18 AM

There are several reasons for the usage of the this keyword:

  • Qualify a member that may be hidden by a similar name
  • For an object to pass itself as a parameter to a method
  • For an object to return itself from a method
  • For declaring indexers
  • For declaring extension methods
  • For passing parameters between constructors

Was This Post Helpful? 1
  • +
  • -

#10 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1251
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 09:20 AM

These two might the ones that are most prominent:

Quote

For an object to pass itself as a parameter to a method
For an object to return itself from a method

Was This Post Helpful? 0
  • +
  • -

#11 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1634
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 09:21 AM

I dont understand your statement, as you cannot create indexers or extension methods without using the this keyword. So what do you mean by prominent?
Was This Post Helpful? 0
  • +
  • -

#12 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1251
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 09:23 AM

I mean he's most likely to use while learning in the beginning.
Was This Post Helpful? 0
  • +
  • -

#13 lookitstom  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 28
  • Joined: 12-July 10

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 09:31 AM

View Poststapia.gutierrez, on 17 July 2010 - 08:16 AM, said:

What error message are you getting? That doesn't make sense because in your code you give x and y values in the constructor. So you be using it like this: Math mathClass = new Math(2,2)

If you use it like this Math mathClass = new Math();, you'll obviously use the default constructor which does nothing to x and y, thus giving you 0 and 0.

hmmmm
in my main method i wrote
Math Add = new Math(6, 3);
Add.doAdd(); // invoke the doAdd method


and so on, and when declaring the variables at the beginning of the program i wrote
 // private variables set here
        private int x = 0;
        private int y = 0;
        private int sum;


so thats like exactly what you told me...

i would have taken a screen shot of the error but the message is in hebrew (which is so weird btw, my windows is in english)... it doesnt say anything to be honest, just like windows cant run the program cause of an error would u like to report it and crap like that
but i'll give you this - (when i get the send/dont send error report message, i clicked dont send and this was written on the screen)
Posted Image
tells ya anything?
Was This Post Helpful? 0
  • +
  • -

#14 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1634
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 09:33 AM

that's not hebrew silly. It's saying that one of your numbers is incorrectly formatted, on line 63. So post all the code so we can see what's going wrong
Was This Post Helpful? 0
  • +
  • -

#15 lookitstom  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 28
  • Joined: 12-July 10

Re: whats wrong with my code + a question about .this keyword

Posted 17 July 2010 - 10:10 AM

View PostPsychoCoder, on 17 July 2010 - 08:33 AM, said:

that's not hebrew silly. It's saying that one of your numbers is incorrectly formatted, on line 63. So post all the code so we can see what's going wrong

no, that message is not hebrew, but the previous one was :P
believe me i know what hebrew is, i live in israel ^.^
Posted Image
so as you can see this is the message i got, and after clicking "dont send report" (the left button) cmd wrote what i posted earlier.

original code -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MathExercise
{
    public class Math

    {
        // private variables set here
        private int x = 0;
        private int y = 0;
        private int sum;
    
        public void doAdd() // Add method
        {
           
            sum = x + y;
            Console.WriteLine("sum of {0} + {1} = {2}",
                                x, y, sum);
        }

        public void doSubtract() // Subtract method
        {
            sum = x - y;
            Console.WriteLine("{0} - {1} = {2} ",
                               x, y, sum);
        }

        public void doMultiply() // Multiply method
        {
            sum = x * y;
            Console.WriteLine("(0} * {1} = {2} ",
                               x, y, sum);
        }

        public void doDivide() // Divide method
        {
            sum = x / y;
            Console.WriteLine("(0} / {1} = {2} ",
                               x, y, sum);
        }

        public Math(int myX, int myY)
        {
            myX = x;
            myY = y;
        }
    }

    public class Tester
    {
        static void Main()
        {
                Math Add = new Math(6, 3);
                Add.doAdd(); // invoke the doAdd method

            Math Subtract = new Math(6, 3);
            Subtract.doSubtract(); //invoke the doSubtract method

            Math Multiply = new Math(6, 3);
           Multiply.doMultiply(); //invoke the doMultiply method

            Math Divide = new Math(6, 3);
            Divide.doDivide(); //invoke the doDivide method
        }

    }
}






i hope you'll find whats wrong

This post has been edited by lookitstom: 17 July 2010 - 10:10 AM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2