c# - one method, different parameters -



c# - one method, different parameters -

if have function operations (that work either 1 of 2 types) , needs work 2 different type parameters, there nice way create public void foo(typex x || typey x)?

example:

void main(bool b) { if(b) { list<int> x = new list<int>(); x.add(5); } else { collection<int> x = new collection<int>(); x.add(5); } foo(x); }

the way see it, leaves 2 options.

option1:

void foo(list<int> x) { console.writeline(x.tostring()); } void foo(collection<int> x) { console.writeline(x.tostring()); }

why not? because if void foo()is longer few rows seems ugly , unnecessary.

option2:

void foo(object x) { console.writeline(x.tostring()); }

why not? works fine simple example, if foo supposed not every object has, x.add(1); error saying object doesn't have method.

does know geniusly gorgeous sollution this? or stuck option1?

in case list<int> , collection<int> both implement ilist<int> interface (among others). so, assuming code not specific 1 or other of these types, should able utilize interface:

void foo(ilist<int> x) { console.writeline(x.tostring()); }

the generalized version of reply - applies classes write - should create interface types in question. assuming have typex , typey state in origin of question:

interface icanfoo { string foo(); } class typex : icanfoo { public string foo() { homecoming "i'm typex!"; } } class typey : icanfoo { public string foo() { homecoming "i'm typey!"; } } void foo(icanfoo x) { console.writeline(x.foo()); }

c# function parameters

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -