-1

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!

Kentalian
  • 25
  • 3
  • 3
    The correct syntax is `void LinkPair(int? val=null)`. There's nothing wrong with it. On the other hand, `public int val = 1;` is wrong - fields are implementation details. Use properties for anything that should be accessible by other classes. Only properties are considered part of a class's API – Panagiotis Kanavos Sep 16 '22 at 11:36
  • Thank you! I don't know why I didn't think I could use nullables as a method parameter. Also sorry, I simplified it too much it seems, I have edited the question. – Kentalian Sep 16 '22 at 11:46
  • Would you mind posting your comment as an answer so I can mark it as correct? – Kentalian Sep 16 '22 at 11:49

1 Answers1

3

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();
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236