Home > OS >  C# alternative to runtime optional parameters?
C# alternative to runtime optional parameters?

Time:09-17

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:

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!

CodePudding user response:

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();
  •  Tags:  
  • c#
  • Related