Can I make a function in C# take an optional parameter or do I need to overload it? -


i have following in interface:

string gettopic(string rk); 

and function:

public string gettopic(string rk) { return string.format("{0}.{1}.{2}", rk.substring(0, 2).trimstart('0'), rk.substring(2, 2).trimstart('0').padleft(1, '0'), rk.substring(4, 2).trimstart('0').padleft(1, '0')); } 

i add optional second parameter, enabling function called this:

var = gettopic("010101") 

or

var b = gettopic("010101","test") 

in first case output "1.1.1" , in second case output "1.1.1 - test".

is possible or need make 2 functions , have 1 overload other one? how can specify optional second parameter in interface?

you can set default:

public string gettopic(string rk, string anotherparam = "") { string append = (string.isnullorempty(anotherparam)) ? "" : " - " + anotherparam; return string.format("{0}.{1}.{2}{3}", rk.substring(0, 2).trimstart('0'), rk.substring(2, 2).trimstart('0').padleft(1, '0'), rk.substring(4, 2).trimstart('0').padleft(1, '0'), append); } 

so "anotherparam" test if call:

var = gettopic("010101"); 

and interace-definition:

public interface iutilityservice { string gettopic(string rk, string suffix = ""); } 

msdn: http://msdn.microsoft.com/de-de/library/dd264739.aspx


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -