Monday, 15 March 2010

var - Define variable type conditionally C# -



var - Define variable type conditionally C# -

in "ado.net entity info model" have created "database first" model number of tables. tables have "code" , "name" fields , different set of other fields. i've created "context" object. want create variable "src_table", assigned context.table1 or context.table2 etc conditionally , work src_table.code , src_table.name properties.

a code 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 have no thought how give chance take table:

var context = new postgresentities(); console.writeline("enter 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 way it?

one alternative define abstractions , utilize when need access table.

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

implement interfaces on 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 utilize them

var context = new postgresentities(); console.writeline("enter 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);

c# var implicit-typing

No comments:

Post a Comment