Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

The as operator must be used with a reference type or nullablepe or nullable type ('long' is a non-n

Discussion in 'Scripting' started by qcw27710, Nov 30, 2019.

  1. qcw27710

    qcw27710

    Joined:
    Jul 9, 2019
    Posts:
    139
    Code (CSharp):
    1. public void InformNetwork(Vetr eventName, params object[] adder) {
    2.     switch (eventName)
    3.     {
    4.         case Vetr.CLOSED:
    5.             long connId = adder[0] as long ?? throw new Exception("Empty or invalid connId (Connection ID)");
    I'm looking for a single liner to grab a variable, cast it to a type (in this case
    long
    ) and throw if it's either null or cast/assignment is not successful. I thought that was a way to do it but for some reason it fails. It won't even compile with following errors in the console:
    error CS0077: The as operator must be used with a reference type or nullable type ('long' is a non-nullable value type)
     
  2. qcw27710

    qcw27710

    Joined:
    Jul 9, 2019
    Posts:
    139
    Welp, I'm an idiot, forgot
    ?
    after
    long
    . So now it's:
    long connId = adder[0] as long? ?? throw
    and works.
     
    Kurt-Dekker likes this.