Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# alternative to runtime optional parameters?

I’m not sure how to go about doing this, after a bit of research I couldn’t really find something that fits my needs. The only thing I could find is from another coding language entirely. I think I might be over-complicating things but I’m blanking and can’t seem to wrap my head around this problem.

Here’s a simplified example of what I’m trying to achieve, say I have a class Item:

public class Item {
    public int val { get; set; } = 1;
    public void Link(Item i) { ... }
}

And in some other class that manages Items, I have this method:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void LinkPair(int val = GetLowestVal()) {
    var pair = GetItems(val);
    pair[0].Link(pair[1]);
}

Basically what I want it to do is: if given a value val, find and link a pair of Items with matching values, otherwise just link a pair both with the lowest value in the list. Unfortunately void LinkPair(int val = GetLowestTier()) isn’t a valid signature. Also, since val is an int I can’t set its default to null, otherwise I would so something like this I presume:

void LinkPair(int val = null) {
    val = val ?? GetLowestVal();
    ...

I’d like to avoid having to create another overloaded method since I might end up with quite a few variations of these. Any help would be appreciated!

>Solution :

You can’t assign null to an int. You’ll have to use int?

void LinkPair(int? val = null) {
    val = val ?? GetLowestVal();

If you know that val will never be 0 you can use this as the default :

void LinkPair(int val = 0) {
    val =  val!=0? val : GetLowestVal();

0 is the default for numbers so this is equivalent to :

void LinkPair(int val = default) {
    val =  val!=0 ? val : GetLowestVal();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading