Compiler error

Hello. I am not sure if this is the right thread to post. If not please direct me to the right one :).

I have following incorrect compiler behavior in VS2005/C#

following property implementation produce compilation error:
class A
{
private bool flag;
...
public DateTime MyTime
{
get { return flag DateTime.Now : null; }
}

while the following code does not:
class A
{
private bool flag;
...
public DateTime MyTime
{
get { if (flag) return DateTime.Now else null; }
}




Answer this question

Compiler error

  • moff

    Minherz wrote:

    class A
    {
    private bool flag;
    ...
    public DateTime MyTime
    {
    get { return flag DateTime.Now : null; }
    }


    This gives you error because your are returning null in one of 2 cases.

    Minherz wrote:

    while the following code does not:
    class A
    {
    private bool flag;
    ...
    public DateTime MyTime
    {
    get { if (flag) return DateTime.Now else null; }
    }

    This doesnot gives you any error becuase you are not retuning null in any case even in false because you are not using the return keyword.

    Reason: DateTime is a Structure and in C# structures are value types and Classes are Reference type by default in C#. A Structure can never have a null value unlike classes and to initilize a structure you dont need to use new keyword becuse its already instantiated to it default value when you declare it unlike class when you declarean object of it, it has a null refence until you use new keyword to instantiate it.

    I hope this is quite simple and to the point explaination of your problem!

    Best Regards,



  • abhas

    The problem lies within the fact the code is using the operator to return the result. By its nature it has to return similar values. Since DateTime is not a Non Nullable value by default the compiler is picking up on that and producing the error

    error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and '<null>'

    Now the code provided is designed to return a value type that can be initialized to null, via the public DateTime , which is the goal of the code...but the compiler does use that to trump the operator processing. You will have to do without the operator in this situation due to the design needed by the processing.


  • TopDean

    The last code also produces compilation error. See, you format it:

    get
    {
    if (flag)
    return DateTime.Now //<--- shoud have ;
    else
    null; <---- should have return
    }

  • Olavo

    Please show us the error message.

    --
    SvenC


  • THE RAZI

    try to understand now...... your property which u r defining by name MyTime is of Nullable DateTime type ok but DateTime.Now which u r returning is not Nullable that is simple System.DateTime type okkkkkkkkkk hope so u find the answer


  • Compiler error