Search code examples
c#if-statementinstantiationnullable-reference-types

if..else if..else expression for non nullable reference types


I am curious how one would create a simple non nullable reference type in cases where assignment depends on an if..else if...else expression. Ternary operators work great for simple if...else cases, the new C#8 switch syntax works great for constants but what about run time?

For example, Kotlin provides something like this:

fun Test(value: Int) : String {
  val num: Int = Random.nextInt(0, 100)
  val message: String = if (value > num) { //message cannot be null here
    "greater than"
  } else if(value < num) {
    "less than"
  } else {
    "equal to"
  }
  return message
}

So with a C# non nullable reference type, how could I do the same thing? Would I have to build a factory to instantiate this non nullable string? Or use a dummy value initially for an if..else if..else block?


Solution

  • You do not need to initialize a variable, as long it is definitely assigned. I.e. this is legal

    string Test(bool b){
        string result;
        if(b){ result = "true"}
        else { result = "false"}
        return result;
    }