Results 1 to 6 of 6

Thread: which is better code

  1. #1

    Thread Starter
    Fanatic Member popskie's Avatar
    Join Date
    Jul 2005
    Location
    In my chair
    Posts
    666

    which is better code

    Look at the code below.

    Code:
    ((Form1(this.Owner).textBox1.Text  = "new value";
    ((Form1(this.Owner).textBox2.Text  = "new value";
    ((Form1(this.Owner).textBox3.Text  = "new value";
    vs

    Code:
    Form1 f1 = (Form1)this.Owner;
    f1.textBox1.Text  = "new value";
    f1.textBox2.Text  = "new value";
    f1.textBox3.Text  = "new value";

    thanks

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: which is better code

    The second one because it's less resource intensive. If you have to use the same property value more than once, in your case Owner, it's more efficient to assign it to a local variable and use that. That's because a property is actually a get and a set method, so if you're accessing the same property twice you're calling the same method twice. Calling a method is more resource intensive than creating a local variable.

    Having said that, if you're only using the property value twice then you might choose to forgo the local variable for brevity. Any more than twice though and I'd definitely use the variable.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    Fanatic Member Bombdrop's Avatar
    Join Date
    Apr 2001
    Location
    St Helens, England, UK
    Posts
    667

    Re: which is better code

    I agree with jmcilhinney totally and the second method is also more firendley on the eyes.

  4. #4
    Registered User RaviIntegra's Avatar
    Join Date
    Mar 2007
    Location
    Pondicherry, India
    Posts
    125

    Re: which is better code

    Second method is the best. I agree with jmcilhinney.

  5. #5
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: which is better code

    I agree with jmcilhinney. I also think he's way cool.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  6. #6
    Hyperactive Member drattansingh's Avatar
    Join Date
    Sep 2005
    Posts
    395

    Re: which is better code

    jmcilhinney is there anything you don't know???

    I put you in my "cool book" a long time ago!

    Jennifer

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width