plavozont
plavozont

Reputation: 813

Define variable type conditionally C#

In "ADO.NET Entity Data Model" I have created a "database first" model from a number of tables. All tables have "code" and "name" fields and different set of other fields. Then I've created a "context" object. Now I want to create a variable "src_table", which will be assigned to context.table1 or context.table2 etc conditionally and then work with src_table.code and src_table.name properties.

A code like this works fine:

var context = new postgresEntities();
var src_table = context.table1;
foreach (var src_table_rec in src_table)
{
  Console.WriteLine("Code: {0}, Name: {1}", src_table_rec.code, src_table_rec.name);
}

Or this:

var context = new postgresEntities();
var src_table = context.table2;
foreach (var src_table_rec in src_table)
{
  Console.WriteLine("Code: {0}, Name: {1}", src_table_rec.code, src_table_rec.name);
}

But I have no idea how to give the opportunity to choose the table:

var context = new postgresEntities();

Console.WriteLine("Enter the table number:");
string response = Console.ReadLine();
int n;
bool isNumeric = int.TryParse(response, out n);

if (isNumeric && n==1)
{
  var src_table = context.table1;
} 
else if (isNumeric && n==2)
{
  var src_table = context.table2;
} 
else
{
  Console.WriteLine("Table number {0} doesn't exist.", n);
}

foreach (var src_table_rec in src_table)
{
  Console.WriteLine("Code: {0}, Name: {1}", src_table_rec.code, src_table_rec.name);
}

Is there a way to do it?

Upvotes: 0

Views: 2110

Answers (1)

Maarten
Maarten

Reputation: 22945

One option is to define abstractions and use those when you need to access the table.

public interface ITable {
    string code { get; set; }
    string name { get; set; }
}

Implement the interfaces on your tables

public class Table1: ITable {
    public string code { get; set; }
    public string name { get; set; }
}

public class Table2: ITable {
    public string code { get; set; }
    public string name { get; set; }
}

And use them

var context = new postgresEntities();

Console.WriteLine("Enter the table number:");
string response = Console.ReadLine();
int n;
bool isNumeric = int.TryParse(response, out n);

ITable src_table = null;

if (isNumeric && n==1) {
    src_table = context.table1;
} else if (isNumeric && n==2) {
    src_table = context.table2;
} else {
  Console.WriteLine("Table number {0} doesn't exist.", n);
}

Console.WriteLine("Code: {0}, Name: {1}", src_table.code, src_table.name);

Upvotes: 1

Related Questions