C # - Initialize a variable without knowing what it will be

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 { //make the change and update the database and gridview } catch (InvalidOperationException) { } } 

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.

+4
source share
5 answers

In C #, all types need a type. If your Table# types are extended by DataModel.DataAccess.Table , use this:

 DataModel.DataAccess.Table currentValue; 

Otherwise, you will need to find a common base class (an object that is plausible of them).

 object currentValue; 

Since you did not initialize currentValue , the compiler cannot know what type you mean by var . That is why you get an exception.

Addition. Perhaps instead of passing the table name, you can use a generic method, for example:

 moveUp(dc.Table1, item => item.Table1Key, "george"); void moveUp<T> (IEnumerable<T> table, Func<T,string> keySelector, string ValId) { T currentValue = table.Single(item => keySelector(item) == ValueId); try { //make the change and update the database and gridview } catch (InvalidOperationException) { } } 
+7
source

Use a type object instead of var, although I would probably rewrite the whole process and use consistent (and standard) naming conventions.

So:

 object currentValue = null; 
+2
source

You can try writing an interface that uses each object and a function that accepts that interface.

 public interface ISortableEntity { int ID { get; set; } int SortOrder { get; set; } } public class DataFunctions { public static void MoveUp(string dbName, int valID) { var db = //Get your context here; List<KeyValuePair<string, object>> keys = new List<KeyValuePair<string, object>>(); keys.Add(new KeyValuePair<string, object>("ID", valID)); ISortableEntity entity = db.GetObjectByKey(new System.Data.EntityKey(dbName, keys)) as ISortableEntity; if (entity != null) { entity.SortOrder += 1; } db.SaveChanges(); } } 
+2
source

You do not know the type of variable, so you declare it implicitly ("var", as opposed to, say, "int")?

You do not need to initialize explicit types - implicit types require this because they determine their type by a given value.

0
source

The solution is interfaces. The classes Table 1 and Table 2 must implement an interface (for example, ISortableTable or whatever you want to call) with the CurrentValue property. Table 1. Implementing the CurrentValue property will return the correct result for Table1 and Table2. The CurrentValue property will return the correct result for Table2. Then your sort function can work with any class that implements ISortableInterface and works with the corresponding property of the CurrentValue object.

0
source

All Articles