I have two different tables in my database, and each of them is displayed to the user based on their "SortOrder". I wrote two functions that take a string (or entity) and change the sort order with the one closest to it (up or down, depending on which function is executed). I need these functions to work for two different tables, depending on where the event occurs (multiple gridviews with identical functionality). Here is what I still have (again, there is an almost identical function for moving down, but I will not post this because it will be redundant):
protected void moveUp(String ValId, String dbName) { int ValueId = Convert.ToInt32(ValId); DataModel.DataAccess.Entities dc = new DataModel.DataAccess.Entities(); if (dbName.ToLower() == "table1") { DataModel.DataAccess.Table1 currentValue = dc.Table1.Single(table1item => table1item.Table1ItemId == ValueId); } else if (dbName.ToLower() == "table2") { DataModel.DataAccess.Table2 currentValue = dc.Table2.Single(table2item => table2item.Table2ItemId == ValueId); } try {
The obvious problem is that I need to initiate the currentValue variable before the if statements, otherwise there is a βpossibilityβ to never declare it, and therefore the rest of the function (which uses the currentValue variable) will not work.
My question is this: how to initialize a variable before if operations, if I'm not sure what it will be? I thought this might work, but he says I still need to initialize it ("implicitly typed local variables must be initialized"):
var currentValue; //this is the line where I get the error message above if (dbName.ToLower() == "table1") { currentValue = (DataModel.DataAccess.Table1)dc.Table1.Single(table1item => table1item.Table1ItemId == ValueId); } else if (dbName.ToLower() == "table2") { currentValue = (DataModel.DataAccess.Table2)dc.Table2.Single(table2item => table2item.Table2ItemId == ValueId); }
[EDIT] Changed the name to more accurately reflect my question.
source share