c# - Down Sides to Using Properties as Opposed to Method Variables -


i debating pros , cons of couple of utility classes have. classes have couple of properties set prior calling class methods. however, wondering if there cons approach rather sending variable along method call? there typically 1 or 2 methods in these classes.

thank you.

i don't know class looks like, i'll make guess...

i assume have that:

public class myclass {     public static int x { get; set; }      public static void mymethod()     {         console.writeline("x = {0}", x);     } } 

and call this:

myclass.x = 42; myclass.mymethod(); 

there @ least 2 problems approach:

  • there no obvious indication need set x before calling mymethod
  • it makes method non thread-safe: if both thread1 , thread2 calling it, can have that:

    thread1 sets x 42 thread2 sets x 99 thread1 calls mymethod => prints 99 instead of 42 thread2 calls mymethod => prints 99

a better approach pass value parameter method:

public class myclass {     public static void mymethod(int x)     {         console.writeline("x = {0}", x);     } } 

and call this:

myclass.mymethod(42); 

this solves 2 problems mentioned before:

  • it's clear need provide value of x mymethod
  • there no state stored in class, method thread-safe

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -