Tutorial :Use Variable of a function in another function without parameters?



Question:

i like to make my database insert more dynamicly with functions.

Like this:

private void setValues() {     string test  = "foo";     string test2 = "bar";  }  private void WriteToDB() {      dc dcOfMyDatabase = new dc();        DBTable myTable = DbTable() {          field1 = test; // values of other function          field2 = test2; // values of other function              }  }  private void doAll() {      setValues();      WriteToDB();  }  

Of Course i can do it with parameters in WriteToDB()... But I have so many fields and hope it works with another clean way.

Im sure there is one correct way for a clean developping something like this.

Thanks and regards.


Solution:1

You can promote them to class members or properties:

string test;    private void setValues() {     test  = "foo";  }  

or:

string test {get; set;}  

You should read about Object Oriented design and programming - this will certifiably help you organize your code in a more logical way.


Solution:2

The correct way is indeed to pass parameters to WriteToDB. If the problem is that you have many parameters, wrap them in a containing class, and pass an instance of this class to your writing function.

Also, consider if using an ORM engine (such as LINQ to SQL or NHIbernate) instead of direct database access classes could be helpful for you.


Solution:3

I'm unsure of what you are trying to do here. Your code snippet has some errors in it and would not compile if you tried to run it.

That being said, if you're looking for a mapping from code to DB I would check out Linq To SQL. Here's a short introduction.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »