Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does making this getter nullable cause a compile error?

Tags:

c#

c#-6.0

This code works:

class Example
{
    public Int32 Int32
    {
        get { return Int32.Parse("3"); }
    }
}

This code does not compile:

class Example
{
    public Int32? Int32
    {
        get { return Int32.Parse("3"); }
    }
}

CS1061 'int?' does not contain a definition for 'Parse' and no extension method 'Parse' accepting a first argument of type 'int?' could be found (are you missing a using directive or an assembly reference?)


My example may look silly, but it makes a lot more sense if you use imagine an enum, like

public Choice? Choice { get { return Choice.One; } }
like image 369
default.kramer Avatar asked Jun 14 '16 20:06

default.kramer


1 Answers

In second example Int32 refers to property Int32 not to type System.Int32. And since the property Int32 is of type System.Nullable(System.Int32), it doesn't have a parse method.

You'll have to write,

public Int32? Int32
{
    get { return System.Int32.Parse("3"); }
}
like image 138
Jonathan Allen Avatar answered Oct 07 '22 17:10

Jonathan Allen