简体   繁体   中英

Nullable or default value?

What class should I use?

public class Category
{
    public int Id {get;set;}
    public int IdParent {get;set;}
    public string Title {get;set;}
}
or
public class Category
{
    public int Id {get;set;}
    public Nullable<int> IdParent {get;set;}
    public string Title {get;set;}
}

Take into account that auto increment starts from 1 and category can be without parent category.

If it can be without a parent, you want nullable.

To make your code more readable, you can do:

public class Category
{
    public int Id {get;set;}
    public int? IdParent {get;set;}
    public string Title {get;set;}
}

(Edit: Also, the class declaration shouldn't have parens)

The Nullable<int> conveys the intent much better than the use of a default value, so I would definitely use it instead of checking for zero. It also makes the check for nullness required, whereas if you are using a default value you may forget to do the check.

In case you do decide to go with zero as a "no parent", you should define a named constant for it:

public class Category
{
    public const int NoParent = 0;
    public int Id {get;set;}
    public int IdParent {get;set;}
    public string Title {get;set;}
}

I'm not sure what you're trying to do, but if you want to use this to insert with auto increments you probably want your id to be nullable too.

public class Category
{
    public int? Id { get; set; }
    public int? IdParent { get; set; }
    public string Title { get; set; }
}

I would use the second option, because it better communicates the fact that a category can have no parent. With the first option, you need to use a magic value to indicate a missing parent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM