I came across an interesting facet of the C# language this morning I have not experienced yet; consider the below code snippet:
public class Example
{
public int getInt()
{
int? myInt = 2;
return myInt; // <-- compiler error.
}
public object getObject()
{
object? obj = new { };
return obj; // <-- OK, no error.
}
}
The compiler returns an error on the commented line above:Error CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?) (CS0266)
What I find interesting is that the object example works just fine without complaining. I am assuming this is something to do with primitives vs. objects but I am unable to find any resources. I am aware the return type is not matching the object type, I just thought it was curious that it works with objects and not a primitive. If anyone could share some links/provide an explanation as to why this is, it would be greatly appreciated.